第四部分,编写你的第一个Django应用

前文再续书接上回教程3. 我们继续编写网络问卷应用,并专注于简单的form处理并减少代码量。

编写一个简单窗体

让我们把在上一节教程中的(“polls / detail.html”)内容更新下,在模板中添加一个一个 <form>组件:

polls/templates/polls/detail.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>

A quick rundown:

  • 上面的模板为每个问题显示一个单选按钮。 每个单选按钮的value是与之关联的问题的ID。 每个单选按钮的name是问题的"choice". 这意味着,当用户选择了某个单选按钮并提交表单后,程序会以POST方式将choice=#发送至服务器,“#”是选中选择的ID。 This is the basic concept of HTML forms.
  • 我们将表单的action设置为{% url {poll:'vote' question.id %},然后我们设置method =“post” 使用method="post"(而不是使用method="get")很重要,因为提交表单会对服务器数据进行更改。 当需要提交数据值服务器端做数据更改(提交新数据、更改以往的数据等)时,使用method="post". 这种方式不止是针对于Django,而是Web开发的通用实践。
  • forloop.counter表示for标签经过了多少次循环
  • Since we’re creating a POST form (which can have the effect of modifying data), we need to worry about Cross Site Request Forgeries. Thankfully, you don’t have to worry too hard, because Django comes with a very easy-to-use system for protecting against it. 简而言之,所有以内部URL作为目标的POST表单应当使用{% csrf_token %}模板标签。

接下来,我们需要创建Django视图来处理提交的数据。 还记得吗,在教程3中,我们为问卷调查应用创建了以下的URLconf:

polls/urls.py
path('<int:question_id>/vote/', views.vote, name='vote'),

We also created a dummy implementation of the vote() function. Let’s create a real version. Add the following to polls/views.py:

polls/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
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,)))

This code includes a few things we haven’t covered yet in this tutorial:

  • request.POST是一个类似字典的对象,允许您通过键名访问提交的数据。 在这例子中, request.POST ['choice']以字符串形式返回所选选项的ID。 request.POST值始终是字符串。

    Note that Django also provides request.GET for accessing GET data in the same way – but we’re explicitly using request.POST in our code, to ensure that data is only altered via a POST call.

  • 如果POST数据中没有提供choicerequest.POST ['choice']将会引发KeyError The above code checks for KeyError and redisplays the question form with an error message if choice isn’t given.

  • After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect接受一个参数:用户将被重定向到的URL(在这种情况下,我们如何构造URL)。

    As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s just good Web development practice.

  • We are using the reverse() function in the HttpResponseRedirect constructor in this example. This function helps avoid having to hardcode a URL in the view function. It is given the name of the view that we want to pass control to and the variable portion of the URL pattern that points to that view. In this case, using the URLconf we set up in Tutorial 3, this reverse() call will return a string like

    '/polls/3/results/'
    

    where the 3 is the value of question.id. This redirected URL will then call the 'results' view to display the final page.

As mentioned in Tutorial 3, request is an HttpRequest object. For more on HttpRequest objects, see the request and response documentation.

有人在问题中投票后,vote()视图重定向到问题的results页面。 我们来修改下这个视图:

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})

This is almost exactly the same as the detail() view from Tutorial 3. The only difference is the template name. We’ll fix this redundancy later.

Now, create a polls/results.html template:

polls/templates/polls/results.html
<h1>{{ question.question_text }}</h1>

<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>

Now, go to /polls/1/ in your browser and vote in the question. You should see a results page that gets updated each time you vote. If you submit the form without having chosen a choice, you should see the error message.

Note

The code for our vote() view does have a small problem. It first gets the selected_choice object from the database, then computes the new value of votes, and then saves it back to the database. If two users of your website try to vote at exactly the same time, this might go wrong: The same value, let’s say 42, will be retrieved for votes. Then, for both users the new value of 43 is computed and saved, but 44 would be the expected value.

This is called a race condition. If you are interested, you can read Avoiding race conditions using F() to learn how you can solve this issue.

使用通用视图:优化代码

The detail() (from Tutorial 3) and results() views are very simple – and, as mentioned above, redundant. The index() view, which displays a list of polls, is similar.

These views represent a common case of basic Web development: getting data from the database according to a parameter passed in the URL, loading a template and returning the rendered template. Because this is so common, Django provides a shortcut, called the “generic views” system.

Generic views abstract common patterns to the point where you don’t even need to write Python code to write an app.

让我们完善我们的投票应用程序使用通用的意见系统,所以我们可以删除一堆我们已有的代码。 We’ll just have to take a few steps to make the conversion. We will:

  1. 修改URLconf。
  2. Delete some of the old, unneeded views.
  3. Introduce new views based on Django’s generic views.

Read on for details.

为什么要重构?

Generally, when writing a Django app, you’ll evaluate whether generic views are a good fit for your problem, and you’ll use them from the beginning, rather than refactoring your code halfway through. But this tutorial intentionally has focused on writing the views “the hard way” until now, to focus on core concepts.

You should know basic math before you start using a calculator.

Amend URLconf

First, open the polls/urls.py URLconf and change it like so:

polls/urls.py
from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

Note that the name of the matched pattern in the path strings of the second and third patterns has changed from <question_id> to <pk>.

Amend views

接下来,我们将删除旧的indexdetailresults视图,并使用Django的通用视图。 To do so, open the polls/views.py file and change it like so:

polls/views.py
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


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, no changes needed.

We’re using two generic views here: ListView and DetailView. Respectively, those two views abstract the concepts of “display a list of objects” and “display a detail page for a particular type of object.”

  • Each generic view needs to know what model it will be acting upon. This is provided using the model attribute.
  • DetailView 通用视图从URL获取一个键值("pk"), 所以我们把 question_id改成 pk

默认情况下,DetailView通用视图使用名为app 名称/ model 名称_detail.html的模板。 In our case, it would use the template "polls/question_detail.html". The template_name attribute is used to tell Django to use a specific template name instead of the autogenerated default template name. 我们还为结果列表视图指定了template_name - 这确保了结果视图和详细视图在呈现时具有不同的外观,即使它们都是 DetailView幕后。

类似地,ListView使用一个叫做app name/model name_list.html的默认模板;我们使用template_name 来告诉ListView 使用我们自己已经存在的"polls/index.html"模板。

In previous parts of the tutorial, the templates have been provided with a context that contains the question and latest_question_list context variables. 对于DetailView ,question变量会自动提供—— 因为我们使用Django 的模型 (Question), Django 能够为context 变量决定一个合适的名字。 However, for ListView, the automatically generated context variable is question_list. To override this we provide the context_object_name attribute, specifying that we want to use latest_question_list instead. 作为一种替代方法,您可以更改模板以匹配新的默认上下文变量 - 但只要告诉Django使用您想要的变量就容易多了。

Run the server, and use your new polling app based on generic views.

For full details on generic views, see the generic views documentation.

When you’re comfortable with forms and generic views, read part 5 of this tutorial to learn about testing our polls app.