之前我们依次介绍了 Models、Admin、URLs、和 Views,本篇再来介绍 Templates,完事之后一个简单但完整的 Django 框架就算是走一遍了,现在我们就来填上篇留下的 polls/index.html、polls/detail.html、polls/results.html
作为最终返回给用户的页面模板,真正想写好还需要前端知识,初次之外还需要掌握 Django 的模板语言
Django 模板语言常用写法:
变量:'{{ }}' 包裹
语句:'{% %}' 包裹,成对出现,{% end... %} 表示到哪儿结束
属性:' . ' 获取,eg:{{ date.attr }}
过滤变量值:用 '|' 进行管道过滤,eg:{{ data.attr|attr:"x,qiex,x"}}
模板继承:格式:'{% extends "base.html" %}'
官方文档:https://docs.djangoproject.com/zh-hans/2.1/topics/templates/
1. 创建 Templates
在 polls 目录下新建名叫 templates 的目录,templates 下再新建叫 polls 的目录,也就是 polls/templates/polls, 最后一个 polls 里面就存放该应用的模板文件
(ps:模板命名空间
虽然我们现在可以将模板文件直接放在
polls/templates
文件夹中(而不是再建立一个polls
子文件夹),但是这样做不太好。Django 将会选择第一个匹配的模板文件,如果你有一个模板文件正好和另一个应用中的某个模板文件重名,Django 没有办法 区分 它们。我们需要帮助 Django 选择正确的模板,最简单的方法就是把他们放入各自的 命名空间 中,也就是把这些模板放入一个和 自身 应用重名的子文件夹里。2. 编写 polls/index.html、polls/detail.html、polls/results.html
新建的 polls 目录是用来存放模板文件(html 格式)的,在 polls 下新建 index.html、polls/detail.html、polls/results.html 文件,即:polls/templates/polls/index.html(对应的polls/detail.html、polls/results.html )
index.html 是用来显示问题索引的,在 Views.IndexView 里面我们知道他接收 Question 数据,且变量名为 question_list
同理分析每个页面对应的 Views、URLs,然后进行编写
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>问题索引</title> </head> <body> {% for question in question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question }}</a></li> {% endfor %} </body> </html>
detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>问题选票详情</title> </head> <body> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> </body> </html>
results.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>选票结果</title> </head> <body> <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> </body> </html>
总结:Templates 模块需要前端知识还有 Django 的模板语言,说起来比较麻烦,我们的目的是把 Django 的整个流程和各部件之间的交互进行介绍演示,因此就不说页面代码了
结果展示:浏览器输入网址:http://127.0.0.1:8000/polls/
点击问题 What's up?进行投票
点击 Vote 提交后查看选票结果(在此之前我为 Not Nuch 投过一票,所以现在是 1:1)
Vote again?可以回到投票界面继续投票
至此,我们就成功利用 Django 实现了一个投票网站了,其实整个Django 的重点,就是最初的这张图,其他的都是写法问题
github:https://github.com/JeesonZhang/django_projects/tree/master/mysite