投票URL
polls/urls.py:
# ex: /polls/5/vote/ url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),
创建投票form表单
polls/templates/polls/detail.html:
{ { question.question_text }}
{% if error_message %}{ { error_message }}
{% endif %}
代码解释:
{
{ forloop.counter }} : for 循环次数{% csrf_token %} : 解决POST请求跨域问题 Cross Site Request Forgeries
{% if %} {% endif %}:判断
{% for %} {% endfor %}:循环
投票Views 逻辑处理
投票 views vote in polls/views.py:
from django.http import HttpResponse, HttpResponseRedirectfrom django.urls import reversedef 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.GET: 分别可获得POST或GET方法的参数值,如上 request.POST['choice'] 可取得POST请求中,name值为choice的Value值。若POST参数中没有choice,则会产生KeyError。
HttpResponseRedirect:重定向跳转,提交成功后进行自动重定向跳转是web 开发的一个良好实践。防止数据提交两次。
投票结果页 Views 逻辑处理
views results in polls/views.py:
from django.shortcuts import get_object_or_404, renderdef results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})
投票结果显示 template
polls/templates/polls/results.html:
{ { question.question_text }}
- {% for choice in question.choice_set.all %}
- { { choice.choice_text }} -- { { choice.votes }} vote{ { choice.votes|pluralize }} {% endfor %}
实现结果
1、访问detail.html:http://localhost:8000/polls/1/
2、选择后,点击vote投票,跳转到结果页 results.html