续教程3,继续更新投票应用程序的模板polls/detail.html,这里使用了HTML中的表单<form>
一、写一个最小的表单
<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>
这个模板为每个问题添加了单选按钮,每个按钮的值对应的是choice的值,每个按钮的名称是choice,意味着当我们选择一个按钮提交表单后,会POST一个选择,where ID=SELECTED_CHOICE_ID
我们把表单的动作设置为{% url 'polls:vote' question.id %},设置post(反向是GET)非常重要,因为提交此表单的行为将改变服务器端的数据。无论何时创建改变服务器端数据的表单,请使用method=“post”。
forloop.counter记录了循环多少次
由于具有提交功能,所以就具有被跨站伪造请求攻击的发现,好在Django提供了一个有用的系统来抵御它,即{%csrf_token%}标志。
在前一个教程中,我们已经设置了urlconf
path('<int:question_id>/vote/', views.vote, name='vote'),
这里我们继续完善polls/views.py中的vote()方法。
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是一个类似字典的对象,request.POST['choice']以字符串形式返回所选选项的ID
Django还提供了请求。GET用于以相同的方式访问GET数据,但我们使用了request.post,以确保数据仅通过POST调用进行更改。
如果POST数据中没有提供选项,request.POST['choice']将引发KeyError。上面的代码会转至KeyError,如果没有给出选择,则重新显示带有错误消息的问题表单。
选择的计数增加后,代码返回一个HttpResponseRedirect,而不是正常的HttpResponse。HttpResponseRedirect只接受一个参数:用户将被重定向,在成功处理POST数据之后,应该始终返回HttpResponseRedirect。
reverse()函数有助于避免在view函数中硬编码URL,会返回一个这样的字符串:
'/polls/3/results/'
3是question.id,重定向的页面会显示'results'
当我们投票后,投票页面会被重定向到结果页面,修改view如下:
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/页面投票查看结果了。
但是目前还存在一个问题,就是如果两个人同时投票,本来数字是42,两个人投完都显示43,那么票数就出现异常了。所以我们需要使用save()或update()来投票,而不是基于页面上的数字。这里使用F()来解决同时投票问题:
from django.db.models import F
#...
selected_choice.votes = F('votes') +1
将selected_choice.votes+=1修改为F可以解决该问题,F是一堆sql指令的结合体。
二、通用视图:用最少的代码做最多的事
写完我们会发现冗余的代码很多,现在我们需要:
1.转换URLconf
2.删除不必要的视图
3.基于通用视图引入新视图
我们需要在设计之初就考虑视图应该是什么样子的,而不是中途再修改代码。
三、编辑 URLconf
经过修改,polls/urls.py修改为:
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>
.
四、修改views
我们现在将旧的index,detail和results视图删除并使用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):
... # 和之前相同
我们在这里使用两个通用视图:ListView和DetailView。这两个视图分别抽象了“显示对象列表”和“显示特定类型对象的详细信息页面”的概念
每个通用视图都需要知道它将作用于什么模型。
DetailView泛型视图希望从URL捕获的主键值被称为“pk”,因此我们将泛型视图的question_id更改为pk。这个视图的模板默认为 <app name>/<model name>_detail.html. 本例子中为“polls/question_detail.html"
template_name属性用于告诉Django使用特定的模板名称,而不是自动生成的默认模板名称。我们还为结果列表视图指定模板名称,这确保了结果视图和细节视图在渲染时具有不同的外观。
前面教程中,我们用context保存问题和问题列表,DetailView会自动提供问题变量,并为其取名。我们使用context_object_name避免了上述操作。告诉Django我们需要哪个变量会更好。
下章将学习测试。