在上一節(jié)的教程中,我們介紹了 Django的視圖,并編寫了一個簡單的實例。本小節(jié)我們將學習網(wǎng)絡投票應用程序,并將側(cè)重于簡單的表單處理,以最少代碼代碼量來實現(xiàn)。
讓我們更新 poll detail 模板(“polls/detail.html”) ,從上個教程,在模板 polls/templates/polls/detail.html 包含一個HTML<form>元素:
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.jixiangtaizi.com.cn # Date : 2020-08-08 <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>上面的模板顯示每個問題選擇一個單選按鈕。每個單選按鈕的值相聯(lián)問題的選擇編號。每個單選按鈕的名稱是“choice”。這意味著,當有人選擇了其中一個單選按鈕并提交表單,它會發(fā)送POST數(shù)據(jù)choice=#,其中#是被選擇的選擇的ID。這是HTML表單的基本概念。 我們設置表單的動作 {% url 'polls:vote' question.id %}, 以及設置 method="post". 使用 method="post" (相對于 method="get") 是非常重要的,因為提交此表將改變服務器端數(shù)據(jù)的行為。當創(chuàng)建一個改變數(shù)據(jù)服務器端表單形式,使用 method="post". 這篇文章并不是只針對 Django; 這是一個很好的 Web 開發(fā)實踐。 forloop.counter表示表單標簽通過多少次循環(huán)了 因為我們正在創(chuàng)建一個POST形式(可以有修改數(shù)據(jù)的影響),我們需要擔心跨站點請求偽造。但是也不必擔心,因為Django自帶了保護對抗的一個非常容易使用的系統(tǒng)??傊?,這是針對內(nèi)部URL所有的POST形式應該使用{%csrf_token%}模板標簽。
我們還創(chuàng)建了一個虛擬實現(xiàn) vote() 函數(shù)?,F(xiàn)在創(chuàng)建一個實用的版本。添加到以下代碼到文件 polls/views.py:
polls/views.py 文件的內(nèi)容如下:
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.jixiangtaizi.com.cn # Date : 2020-08-08 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是一個類似于字典的對象,使您可以通過鍵名訪問提交的數(shù)據(jù)。在這種情況下,request.POST['choice'] 返回被選擇的choice的ID,作為字符串。 request.POST的值總是字符串。
注意:Django還提供 request.GET 以相同的方式訪問 GET數(shù)據(jù) – 但我們明確使用 request.POST 在我們的代碼,以確保數(shù)據(jù)只能通過POST調(diào)用修改。
如果POST數(shù)據(jù)未提供choice,request.POST['choice']將引發(fā)KeyError異常。上面的代碼檢查KeyError異常和錯誤消息顯示問題的表單,如果沒有給出 choice。
選擇choice計數(shù)遞增后,代碼返回 HttpResponse 重定向,而不是一個正常的 HttpResponse。HttpResponseRedirect 需要一個參數(shù):用戶將被重定向到URL(請參閱下面-我們?nèi)绾螛嫿ㄔ谶@種情況下的URL)。
如上Python的注釋所指出的,應該總是在 POST 數(shù)據(jù)處理成功 后返回一個HttpResponse重定向。
在本示例中我們使用的是 HttpResponseRedirect 構造reverse()函數(shù)。此函數(shù)有助于避免硬編碼URL在視圖中。這是因為我們想通過控制并指向該視圖的URL模式的可變部分的視圖的名稱。在這種情況下,使用 URLconf 配置使 reverse()調(diào)用返回字符串如:
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.jixiangtaizi.com.cn # Date : 2020-08-08 '/polls/3/results/'
其中3是question.id的值。然后,這個重定向的URL將調(diào)用“results”視圖中顯示的最后一頁。
現(xiàn)在訪問網(wǎng)址:http://127.0.0.1:8000/polls/1/ 得到結果如下所示:
當有人在一個問題投票后,vote() 視圖重定向到該問題的結果頁面。讓我們編寫這個視圖(polls/views.py):
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.jixiangtaizi.com.cn # Date : 2020-08-08 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})
現(xiàn)在,創(chuàng)建一個 polls/results.html (polls/templates/polls/results.html)模板:
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.jixiangtaizi.com.cn # Date : 2020-08-08 <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>
現(xiàn)在,在瀏覽器中打開 /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'), ]