<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>
简要介绍:
现在,让我们创建一个处理提交的数据的一个 django 视图。
url(r'^(?p<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
我们还创建了一个虚拟实现 vote() 函数。现在创建一个实用的版本。添加到以下代码到文件 polls/views.py:
from django.shortcuts import get_object_or_404, render from django.http import httpresponseredirect, httpresponse from django.core.urlresolvers 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'] 返回被选择的choice的id,作为字符串。 request.post的值总是字符串。
注意:django还提供 request.get 以相同的方式访问 get数据 – 但我们明确使用 request.post 在我们的代码,以确保数据只能通过post调用修改。
如果post数据未提供choice,request.post['choice']将引发keyerror异常。上面的代码检查keyerror异常和错误消息显示问题的表单,如果没有给出 choice。
选择choice计数递增后,代码返回 httpresponse 重定向,而不是一个正常的 httpresponse。httpresponseredirect 需要一个参数:用户将被重定向到url(请参阅下面-我们如何构建在这种情况下的url)。
如上python的注释所指出的,应该总是在 post 数据处理成功后返回一个httpresponse重定向。
在本例中我们使用的是 httpresponseredirect 构造reverse()函数。此函数有助于避免硬编码url在视图中。这是因为我们想通过控制并指向该视图的url模式的可变部分的视图的名称。在这种情况下,使用 urlconf 配置使 reverse()调用返回字符串如:
'/polls/3/results/'
其中3是question.id的值。然后,这个重定向的url将调用“results”视图中显示的最后一页。
现在访问网址:http://127.0.0.1:8000/polls/1/ 得到结果如下所示:
当有人在一个问题投票后,vote() 视图重定向到该问题的结果页面。让我们编写这个视图(polls/views.py):
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 (polls/templates/polls/results.html)模板:
<h2>{{ question.question_text }}</h2> <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/ 并表决的问题。应该会被每次投票时看到更新结果页。如果您提交表单不选择一个选项,应该看到错误消息。
选择选项,提交后显示如下结果:
首先,打开 polls/urls.py 并修改如下:
from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.indexview.as_view(), name='index'), url(r'^(?p<pk>[0-9]+)/$', views.detailview.as_view(), name='detail'), url(r'^(?p<pk>[0-9]+)/results/$', views.resultsview.as_view(), name='results'), url(r'^(?p<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ]
请注意,第二和第三模式的正则表达式匹配的模式名称已经从<question_id>改变为<to>。
接下来,我们要删除旧的 index, detail, 和 results 视图使用django通用视图代替。要做到这一点,打开 polls/views.py 文件并修改它如下:
from django.shortcuts import get_object_or_404, render from django.http import httpresponseredirect from django.core.urlresolvers 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
剩下的你自己发挥了,包教不包会,请参考:https://docs.djangoproject.com/en/1.9/intro/tutorial04/