文章目录
投票应用的下一步: 如何投票?
一个投票的表单
改进detail视图的网页
更新一下投票详细页面的模板 (“polls/detail.html”)
让它包含一个 HTML 元素:
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
{% 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 %}
</fieldset>
<input type="submit" value="Vote">
</form>
legend标签参考这里
简单来说:
该模板在 Question 的每个 Choice 前添加一个单选按钮。
value="{{ choice.id }} 每个单选按钮的 value 属性是对应的各个 Choice 的 id(主键值);
当选择一个单选按钮,并提交表单提交时,它将发送一个 POST 数据 choice=# ,其中# 为选择的 Choice 的 id。
语法中,label的for
值与标签的id
一致,是随后显示的
action 为 {% url ‘polls:vote’ question.id %},method="post"
会改变服务器端的数据.
forloop.counter ,是可以在for内直接使用的变量,指示 for 标签已经循环多少次。从1开始,参考
{% csrf_token %} 模板标签 ,可以防止跨站点请求伪造数据post
其中polls:vote,即指向 polls.url.py中的URLconf 的一项:
path('<int:question_id>/vote/', views.vote, name='vote'),
随即指向 view.py
中的vote函数.它即将完成:
保存选择至数据库,并重定向到
result
视图
创建 vote
视图
将下面的代码添加到 polls/views.py :
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question
# ...
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
简单来说:
request.POST[‘choice’] 以字符串形式返回选择的 Choice 的 ID(即#)。request.POST 是一个类字典对象。
此外,Django 还以同样的方式提供 request.GET 用于访问 GET 数据参考
若无choice ,POST 将引发一个 KeyError 。
增加 Choice 的得票数并保存,之后,代码返回一个 HttpResponseRedirect
HttpResponseRedirect 只接收一个参数:用户将要被重定向的 URL。
使用它而不是HttpResponse是一种惯例
reverse() 函数,用来避免硬编码 URL。参数为:欲跳转视图名称 + args(视图参数)
它将返回'/polls/3/results/'
, 其中, 3即是 question.id 的值
当有人对 Question 进行投票后, vote() 视图将请求重定向到 Question 的结果界面。
编写 result
视图:
- 更改result视图
打开polls/views.py, 更改result函数
from django.shortcuts import get_object_or_404, render
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
- 创建 polls/results.html 模板
<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>
现在,在你的浏览器中访问 /polls/1/ 然后为 Question 投票。你应该看到一个投票结果页面,并且在你每次投票之后都会更新。 如果你提交时没有选择任何 Choice,你应该看到错误信息。
我们的 vote() 视图代码有一个小问题。代码首先从数据库中获取了 selected_choice 对象,接着计算 vote 的新值,最后把值存回数据库。如果网站有两个方可同时投票在 同一时间 ,可能会导致问题。同样的值,42,会被 votes 返回。然后,对于两个用户,新值43计算完毕,并被保存,但是期望值是44。
使用 F() 避免竞争条件
代码还是少点好
存在冗余:
result视图 和 detail() 视图几乎一模一样。唯一的不同是模板的名字。
这些视图反映基本的 Web 开发中的一个常见情况:
根据 URL 中的参数从数据库中获取数据
载入模板文件
然后返回渲染后的模板。
由于这种情况特别常见,Django 提供一种快捷方式,叫做“通用视图”系统。让我们将我们的投票应用转换成使用通用视图系统:
转换 URLconf
打开 polls/urls.py 这个 URLconf 并将它修改成:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
改动:
第二个和第三个匹配准则中,路径字符串中匹配模式的名称已经由
<question_id>
改为<pk>
。
删除一些旧的、不再需要的视图
删除旧的 index, detail, 和 results 视图,并即将用 Django 的通用视图代替。
基于 Django 的通用视图引入新的视图
打开 polls/views.py 文件,并将它修改成:
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
... # same as above, no changes needed.
我们在这里使用两个通用视图: ListView 和 DetailView 。
这两个视图分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。
在具体应用中:
每个通用视图需要知道它将作用于哪个模型。 这由 model 属性提供。
DetailView 期望从 URL 中捕获名为 “pk” 的主键值,所以我们为通用视图把 question_id 改成 pk 。
默认情况下,通用视图 DetailView 使用一个叫做 <app name>/<model name>
_detail.html 的模板。在我们的例子中,它将使用 “polls/question_detail.html” 模板。
template_name 属性是用来告诉 Django 使用一个指定的模板名字,而不是自动生成的默认名字。
我们也为 results 列表视图指定了 template_name —— 这确保 results 视图和 detail 视图在渲染时具有不同的外观,即使它们在后台都是同一个 DetailView 。
类似地,ListView 使用一个叫做 <app name>/<model name>
_list.html 的默认模板;
我们使用 template_name 来告诉 ListView 使用我们创建的已经存在的 “polls/index.html” 模板。
在之前的教程中,提供模板文件时都带有一个包含 question 和 latest_question_list 变量的 context。
对于 DetailView , question 变量会自动提供—— 因为我们使用 Django 的模型(Question), Django 能够为 context 变量决定一个合适的名字。然而对于 ListView, 自动生成的 context 变量是 question_list。
为了覆盖这个行为,我们提供 context_object_name 属性,表示我们想使用 latest_question_list。
作为一种替换方案,你可以改变你的模板来匹配新的 context 变量 —— 这是一种更便捷的方法,告诉 Django 使用你想使用的变量名。
启动服务器,使用一下基于通用视图的新投票应用。
更多关于通用视图的详细信息,请查看 通用视图的文档