defvote(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,)))
解释
pk=request.POST['choice']这个参数表示,从request.POST请求中获取被选择的choice. 如果不存在的话,就抛出一个Choice.DoesNotExistChoice不存在的异常,错误信息为You didn’t select a choice.. 如果存在的话,那么这个choice的votes属性增加1并且使用save()函数写入数据库中. 在完成数据库写入操作之后,向页面发送了一个HttpResponseRedirect,将网页重定向到polls的results上,并且带上了当前的question的id. 这个函数也等效为重定向到'polls/question.id/results'这个页面. 接着我们来完善一下results函数:
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Choice, Question
classIndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' defget_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5]
classDetailView(generic.DetailView): model = Question template_name = 'polls/detail.html'
classResultsView(generic.DetailView): model = Question template_name = 'polls/results.html'
defvote(request, question_id): ... # same as above, no changes needed.
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below. Example 1: