自学python 进击之路 - Django-入门(模板)

167 阅读2分钟

src=http___5b0988e595225.cdn.sohucs.com_images_20190916_32ce26032b124c3cb145a4231627373d.jpeg&refer=http___5b0988e595225.cdn.sohucs.jpg

模板

创建模板

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

Snipaste_2021-06-23_13-48-25.png

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

Snipaste_2021-06-23_13-51-29.png

定义模板

  • 打开templtes/booktest/index.html文件,定义代码如下
  • 在模板中输出变量语法如下,变量可能是从视图中传递过来的,也可能是在模板中定义的
{{变量名}}
  • 在模板中编写代码段语法如下
{%代码段%}
  • 定义模板如下
<html>
<head>
    <title>图书列表</title>
</head>
<body>
<h1>{{title}}</h1>
{%for i in list%}
{{i}}<br>
{%endfor%}
</body>
</html>

视图调用模板

  • 调用模板分为三步骤
  1. 找到模板
  2. 定义上下文
  3. 渲染模板
  • 打开booktst/views.py文件,调用上面定义的模板文件
#coding:utf-8

from django.http import HttpResponse
from django.template import loader,RequestContext

def index(request):
    # 1.获取模板
    template=loader.get_template('booktest/index.html')
    # 2.定义上下文
    context=RequestContext(request,{'title':'图书列表','list':range(10)})
    # 3.渲染模板
    return HttpResponse(template.render(context))
  • 打开浏览器刷新新页面,显得效果如下图

Snipaste_2021-06-23_14-14-41.png

视图调用模板简写

  • 视图调用模板都要执行以上三部分,于是Django提供了一个函数render封装了以上代码
  • 方法render包含3个参数
  1. 第一个参数为request对象
  2. 第二个参数为模板文件路径
  3. 第三个参数为字典,表示向模板中传递的上下文数据
  • 打开booktst/views.py文件,调用render的代码如下
#coding:utf-8

from django.shortcuts import render

def index(request):
    context={'title':'图书列表','list':range(10)}
    return render(request,'booktest/index.html',context)

结束项目

定义视图

  • 编写booktest/views.py文件如下
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

  • 编写booktest/urls.py文件如下
from django.conf.urls import url
#引入视图模块
from . import views
urlpatterns = [
    #配置首页url
    url(r'^$', views.index),
    #配置详细页url,\d+表示多个数字,小括号用于取值,建议复习下正则表达式
    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>