django创建项目案例1详细展示05

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

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

django创建项目案例1详细展示05

show.html代码如下:

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

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

django创建项目案例1详细展示05
django创建项目案例1详细展示05

使用模板

  • 编辑views.py文件,在方法中调用模板代码如下:
#coding:utf-8
from django.shortcuts import render
from 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.objects.all()
    context={'list':bookList}
    return render(request,'booktest/index.html',context)

def show(request,id):
    book=BookInfo.objects.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文件代码目录如下:
    django创建项目案例1详细展示05

代码如下:

#coding:utf-8
from django.conf.urls import url
from . import views


urlpatterns=[
    url(r'^$',views.index),
    url(r'^(\d+)$',views.show)
]
  • 然后运行python manage.py runserver

  • 效果图如下:
    django创建项目案例1详细展示05

django创建项目案例1详细展示05
django创建项目案例1详细展示05

上一篇:关于C#中的DLLImport (引)


下一篇:在Exchange数据库中删除指定邮件