• 接着上一个django创建项目案例1的04继续如下:

定义show.html模板目录如下:

[图片上传失败...(image-3b999b-1531897111035)]

show.html代码如下:

  • 在模板中访问对象成员时,都以属性的方式访问,即方法也不能加括号
<!DOCTYPE html><html lang="en"><head>    <  charset="UTF-8">    < > </ ></head><body><ul>    {%for hero in list%}    <li>{{hero.hname}}</li>    {%endfor%}</ul></body></html>

在hero info里随意添加内容如图:

[图片上传失败...(image-f8d008-1531897111035)]
[图片上传失败...(image-39185e-1531897111035)]

使用模板

  • 编辑views.py文件,在方法中调用模板代码如下:
#coding:utf-8from django.shortcuts import renderfrom django.http import *from .models import *# from django.template import RequestContext,loader# Create your views here.def index(request):    # temp = loader.get_template('booktest/index.html')    # return HttpResponse(temp.render())    bookList=BookInfo. s.all()    context={'list':bookList}    return render(request,'booktest/index.html',context)def show(request,id):    book=BookInfo. s.get(pk=id)    herolist=book.heroinfo_set.all()    context={'list':herolist}    return render(request,'booktest/show.html',context)

知识点介绍

去除模板的硬编码

  • 在index.html模板中,超链接是硬编码的,此时的请求地址为“127.0.0.1/1/”
<a href="{{book.id}}">
  • 看如下情况:将urlconf中详细页改为如下,链接就找不到了
url(r'^book/([0-9]+)/$', views.detail),
  • 此时的请求地址应该为“127.0.0.1/book/1/”
  • 问题总结:如果在模板中地址硬编码,将来urlconf修改后,地址将失效
  • 解决:使用命名的url设置超链接
  • 修改test1/urls.py文件,在include中设置namespace
url(r'^admin/', include(admin.site.urls, namespace='booktest')),
  • 修改booktest/urls.py文件,设置name
url(r'^book/([0-9]+)/$', views.detail, name="detail"),
  • 修改index.html模板中的链接
<a href="{%url 'booktest:detail' book.id%}">

Render简写

  • Django提供了函数Render()简化视图调用模板、构造上下文
  • 修改booktest目录下的urls.py文件代码目录如下:
    [图片上传失败...(image-995f40-1531897111035)]
    代码如下:
#coding:utf-8from django.conf.urls import urlfrom . import viewsurlpatterns=[    url(r'^$',views.index),    url(r'^(d+)$',views.show)]
  • 然后运行python manage.py runserver

  • 效果图如下:
    [图片上传失败...(image-62414-1531897111035)]
    [图片上传失败...(image-c715a3-1531897111035)]
    [图片上传失败...(image-8a6164-1531897111035)]

详细浏览我的博客(https://yq.aliyun.com/users/article?spm=a2c4e.11153940.headeruserinfo.3.24a6291aUNlJjF&do=login)

收藏 打印