更新一下前面编写的投票详细页面的模板("polls/detail.html"),让它包含一个 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>
简要说明:
创建一个 Django 视图来处理提交的数据。在前面我们已经为投票应用创建了一个 URLconf(polls/urls.py文件中),包含:path('<int:question_id>/vote/', views.vote, name='vote'), 还创建了一个 vote() 函数的虚拟现实。将下面代码添加到 polls/views.py
path('<int:question_id>/vote/', views.vote, name='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,)))
正如上面的Python注释所指出的,在成功处理POST数据之后,应该始终返回HttpResponseRedirect。这篇技巧并不是针对Django的;一般来说,它是一个很好的Web开发实践。
在前面代码中,重定向的 URL 将调用 ‘results’ 视图来显示最终的页面。 HTTPRequest 是一个 HTTPRequest 对象,请求和相应的文档
当有人对 Question 投票后,vote() 视图将请求重定向到 Question 的结果界面。 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})
hare 2020.12.16