-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtutorial04.txt
More file actions
201 lines (153 loc) · 8.25 KB
/
tutorial04.txt
File metadata and controls
201 lines (153 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
=====================================
Writing your first Django app, part 4
=====================================
This tutorial begins where :doc:`Tutorial 3 <tutorial03>` left off. We're
continuing the Web-poll application and will focus on simple form processing and
cutting down our code.
Write a simple form
===================
Let's update our poll detail template ("polls/detail.html") from the last
tutorial, so that the template contains an HTML ``<form>`` element:
.. snippet:: html+django
:filename: 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:
* The above template displays a radio button for each question choice. The
``value`` of each radio button is the associated question choice's ID. The
``name`` of each radio button is ``"choice"``. That means, when somebody
selects one of the radio buttons and submits the form, it'll send the
POST data ``choice=#`` where # is the ID of the selected choice. This is the
basic concept of HTML forms.
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we
set ``method="post"``. Using ``method="post"`` (as opposed to
``method="get"``) is very important, because the act of submitting this
form will alter data server-side. Whenever you create a form that alters
data server-side, use ``method="post"``. This tip isn't specific to
Django; it's just good Web development practice.
* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone
through its loop
* 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. In short, all POST
forms that are targeted at internal URLs should use the
:ttag:`{% csrf_token %}<csrf_token>` template tag.
Now, let's create a Django view that handles the submitted data and does
something with it. Remember, in :doc:`Tutorial 3 <tutorial03>`, we
created a URLconf for the polls application that includes this line:
.. snippet::
:filename: polls/urls.py
url(r'^(?P<question_id>[0-9]+)/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``:
.. snippet::
:filename: 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):
"""
There are many ways to write this view.
"""
question = get_object_or_404(Question, pk=question_id)
if request.method == 'POST':
choice_id = request.POST['choice']
selected_choice = question.choice_set.get(pk=choice_id)
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,)))
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
This code includes a few things we haven't covered yet in this tutorial:
* :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
object that lets you access submitted data by key name. In this case,
``request.POST['choice']`` returns the ID of the selected choice, as a
string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
always strings.
Note that Django also provides :attr:`request.GET
<django.http.HttpRequest.GET>` for accessing GET data in the same way --
but we're explicitly using :attr:`request.POST
<django.http.HttpRequest.POST>` in our code, to ensure that data is only
altered via a POST call.
* ``request.POST['choice']`` will raise :exc:`KeyError` if
``choice`` wasn't provided in POST data. The above code checks for
:exc:`KeyError` and redisplays the question form with an error
message if ``choice`` isn't given.
* After incrementing the choice count, the code returns an
:class:`~django.http.HttpResponseRedirect` rather than a normal
:class:`~django.http.HttpResponse`.
:class:`~django.http.HttpResponseRedirect` takes a single argument: the
URL to which the user will be redirected (see the following point for how
we construct the URL in this case).
As the Python comment above points out, you should always return an
:class:`~django.http.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 :func:`~django.urls.reverse` function in the
:class:`~django.http.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 :doc:`Tutorial 3 <tutorial03>`,
this :func:`~django.urls.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 :doc:`Tutorial 3 <tutorial03>`, ``request`` is an
:class:`~django.http.HttpRequest` object. For more on
:class:`~django.http.HttpRequest` objects, see the :doc:`request and
response documentation </ref/request-response>`.
After somebody votes in a question, the ``vote()`` view redirects to the results
page for the question. Let's write that view:
.. snippet::
:filename: 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 :doc:`Tutorial 3
<tutorial03>`. The only difference is the template name. We'll fix this
redundancy later.
Now, create a ``polls/results.html`` template:
.. snippet:: html+django
:filename: 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
:ref:`avoiding-race-conditions-using-f` to learn how you can solve this
issue.
Part 5 is about testing your polls app but we are skipping to :doc:`part 6<tutorial06>` instead to learn about static files management for styling.