上一篇为Django app创建视图(上)写到创建视图,初步创建了index和detail页面,这篇继续写创建视图。首先是创建表单。
创建表单
逻辑与普通页面类似,只不过需要对detail页面进行更新,使其具有提交表单的功能。改写polls/templates/polls/detail.html:
<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>
这里
{% csrf_token %}
用来防止跨站点请求伪造。
{{ forloop.counter }}
用来记录for标记循环的次数
编写视图函数
在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是一个类似于字典的对象,可以让你按关键字名称访问提交的数据。在这种情况下,request.POST[‘choice’]以字符串形式返回所选选项的ID。request.POST值总是字符串。
注意,Django还提供request.GET用于以相同的方式访问GET数据–但是我们显式地使用request.POST在我们的代码中,确保只通过POST调用更改数据。
request.POST如果POST数据中没有提供choice,[‘choice’]将引发KeyError。上面的代码检查KeyError,如果没有给出选择,则重新显示带有错误消息的问题表单。
在计数之后,代码返回一个HttpResponseRedirect,而不是一个普通的HttpResponse。HttpResponseRedirect只接受一个参数:用户将被重定向到的URL。
这是一种很好的Web开发实践,即在成功处理POST数据之后,应该始终返回httpresponseredict。
在本例中,我们在HttpResponseRedirect构造函数中使用reverse()函数。此函数有助于避免在view函数中硬编码URL。它提供了我们要传递控制的视图的名称以及指向该视图的URL模式的变量部分。在本例中,使用我们在教程3中设置的URLconf,这个reverse()调用将返回如下字符串。
results()视图函数
根据业务逻辑,当人提交完表单后,浏览器会跳转到结果页面。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})
创建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>
总结
这部分主要注意为了防止跨站点请求伪造需要加上{% csrf_token %}以及HttpResponseRedirect的重定向