
模板
创建模板
- 为应用booktest下的视图index创建模板index.html,目录结构如下图:

- 设置查找模板的路径:打开test1/settings.py文件,设置TEMPLATES的DIRS值
'DIRS': [os.path.join(BASE_DIR, 'templates')],

定义模板
- 打开templtes/booktest/index.html文件,定义代码如下
- 在模板中输出变量语法如下,变量可能是从视图中传递过来的,也可能是在模板中定义的
{{变量名}}
{
<html>
<head>
<title>图书列表</title>
</head>
<body>
<h1>{{title}}</h1>
{%for i in list%}
{{i}}<br>
{%endfor%}
</body>
</html>
视图调用模板
- 找到模板
- 定义上下文
- 渲染模板
- 打开booktst/views.py文件,调用上面定义的模板文件
from django.http import HttpResponse
from django.template import loader,RequestContext
def index(request):
template=loader.get_template('booktest/index.html')
context=RequestContext(request,{'title':'图书列表','list':range(10)})
return HttpResponse(template.render(context))

视图调用模板简写
- 视图调用模板都要执行以上三部分,于是Django提供了一个函数render封装了以上代码
- 方法render包含3个参数
- 第一个参数为request对象
- 第二个参数为模板文件路径
- 第三个参数为字典,表示向模板中传递的上下文数据
- 打开booktst/views.py文件,调用render的代码如下
from django.shortcuts import render
def index(request):
context={'title':'图书列表','list':range(10)}
return render(request,'booktest/index.html',context)
结束项目
定义视图
from django.shortcuts import render
from models import BookInfo
def index(reqeust):
booklist = BookInfo.objects.all()
return render(reqeust, 'booktest/index.html', {'booklist': booklist})
def detail(reqeust, id):
book = BookInfo.objects.get(pk=id)
return render(reqeust, 'booktest/detail.html', {'book': book})
定义URLconf
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^(\d+)$',views.detail),
]
定义模板
- 编写templates/booktest/index.html文件如下
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>图书列表</h1>
<ul>
{#遍历图书列表#}
{%for book in booklist%}
<li>
{#输出图书名称,并设置超链接,链接地址是一个数字#}
<a href="{{book.id}}">{{book.btitle}}</a>
</li>
{%endfor%}
</ul>
</body>
</html>
- 编写templates/booktest/detail.html文件如下
<html>
<head>
<title>详细页</title>
</head>
<body>
{#输出图书标题#}
<h1>{{book.btitle}}</h1>
<ul>
{#通过关系找到本图书的所有英雄,并遍历#}
{%for hero in book.heroinfo_set.all%}
{#输出英雄的姓名及描述#}
<li>{{hero.hname}}---{{hero.hcontent}}</li>
{%endfor%}
</ul>
</body>
</html>