| 1 |
===================================== |
| 2 |
Writing your first Django app, part 4 |
| 3 |
===================================== |
| 4 |
|
| 5 |
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're |
| 6 |
continuing the web-poll application and will focus on form processing and |
| 7 |
cutting down our code. |
| 8 |
|
| 9 |
.. admonition:: Where to get help: |
| 10 |
|
| 11 |
If you're having trouble going through this tutorial, please head over to |
| 12 |
the :doc:`Getting Help</faq/help>` section of the FAQ. |
| 13 |
|
| 14 |
Write a minimal form |
| 15 |
==================== |
| 16 |
|
| 17 |
Let's update our poll detail template ("polls/detail.html") from the last |
| 18 |
tutorial, so that the template contains an HTML ``<form>`` element: |
| 19 |
|
| 20 |
.. code-block:: html+django |
| 21 |
:caption: ``polls/templates/polls/detail.html`` |
| 22 |
|
| 23 |
<form action="{% url 'polls:vote' question.id %}" method="post"> |
| 24 |
{% csrf_token %} |
| 25 |
<fieldset> |
| 26 |
<legend><h1>{{ question.question_text }}</h1></legend> |
| 27 |
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} |
| 28 |
{% for choice in question.choice_set.all %} |
| 29 |
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> |
| 30 |
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> |
| 31 |
{% endfor %} |
| 32 |
</fieldset> |
| 33 |
<input type="submit" value="Vote"> |
| 34 |
</form> |
| 35 |
|
| 36 |
A quick rundown: |
| 37 |
|
| 38 |
* The above template displays a radio button for each question choice. The |
| 39 |
``value`` of each radio button is the associated question choice's ID. The |
| 40 |
``name`` of each radio button is ``"choice"``. That means, when somebody |
| 41 |
selects one of the radio buttons and submits the form, it'll send the |
| 42 |
POST data ``choice=#`` where # is the ID of the selected choice. This is the |
| 43 |
basic concept of HTML forms. |
| 44 |
|
| 45 |
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we |
| 46 |
set ``method="post"``. Using ``method="post"`` (as opposed to |
| 47 |
``method="get"``) is very important, because the act of submitting this |
| 48 |
form will alter data server-side. Whenever you create a form that alters |
| 49 |
data server-side, use ``method="post"``. This tip isn't specific to |
| 50 |
Django; it's good web development practice in general. |
| 51 |
|
| 52 |
* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone |
| 53 |
through its loop |
| 54 |
|
| 55 |
* Since we're creating a POST form (which can have the effect of modifying |
| 56 |
data), we need to worry about Cross Site Request Forgeries. |
| 57 |
Thankfully, you don't have to worry too hard, because Django comes with a |
| 58 |
helpful system for protecting against it. In short, all POST forms that are |
| 59 |
targeted at internal URLs should use the :ttag:`{% csrf_token %}<csrf_token>` |
| 60 |
template tag. |
| 61 |
|
| 62 |
Now, let's create a Django view that handles the submitted data and does |
| 63 |
something with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we |
| 64 |
created a URLconf for the polls application that includes this line: |
| 65 |
|
| 66 |
.. code-block:: python |
| 67 |
:caption: ``polls/urls.py`` |
| 68 |
|
| 69 |
path("<int:question_id>/vote/", views.vote, name="vote"), |
| 70 |
|
| 71 |
We also created a dummy implementation of the ``vote()`` function. Let's |
| 72 |
create a real version. Add the following to ``polls/views.py``: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
:caption: ``polls/views.py`` |
| 76 |
|
| 77 |
from django.db.models import F |
| 78 |
from django.http import HttpResponse, HttpResponseRedirect |
| 79 |
from django.shortcuts import get_object_or_404, render |
| 80 |
from django.urls import reverse |
| 81 |
|
| 82 |
from .models import Choice, Question |
| 83 |
|
| 84 |
|
| 85 |
# ... |
| 86 |
def vote(request, question_id): |
| 87 |
question = get_object_or_404(Question, pk=question_id) |
| 88 |
try: |
| 89 |
selected_choice = question.choice_set.get(pk=request.POST["choice"]) |
| 90 |
except (KeyError, Choice.DoesNotExist): |
| 91 |
# Redisplay the question voting form. |
| 92 |
return render( |
| 93 |
request, |
| 94 |
"polls/detail.html", |
| 95 |
{ |
| 96 |
"question": question, |
| 97 |
"error_message": "You didn't select a choice.", |
| 98 |
}, |
| 99 |
) |
| 100 |
else: |
| 101 |
selected_choice.votes = F("votes") + 1 |
| 102 |
selected_choice.save() |
| 103 |
# Always return an HttpResponseRedirect after successfully dealing |
| 104 |
# with POST data. This prevents data from being posted twice if a |
| 105 |
# user hits the Back button. |
| 106 |
return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) |
| 107 |
|
| 108 |
This code includes a few things we haven't covered yet in this tutorial: |
| 109 |
|
| 110 |
* :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like |
| 111 |
object that lets you access submitted data by key name. In this case, |
| 112 |
``request.POST['choice']`` returns the ID of the selected choice, as a |
| 113 |
string. :attr:`request.POST <django.http.HttpRequest.POST>` values are |
| 114 |
always strings. |
| 115 |
|
| 116 |
Note that Django also provides :attr:`request.GET |
| 117 |
<django.http.HttpRequest.GET>` for accessing GET data in the same way -- |
| 118 |
but we're explicitly using :attr:`request.POST |
| 119 |
<django.http.HttpRequest.POST>` in our code, to ensure that data is only |
| 120 |
altered via a POST call. |
| 121 |
|
| 122 |
* ``request.POST['choice']`` will raise :exc:`KeyError` if |
| 123 |
``choice`` wasn't provided in POST data. The above code checks for |
| 124 |
:exc:`KeyError` and redisplays the question form with an error |
| 125 |
message if ``choice`` isn't given. |
| 126 |
|
| 127 |
* ``F("votes") + 1`` :ref:`instructs the database |
| 128 |
<avoiding-race-conditions-using-f>` to increase the vote count by 1. |
| 129 |
|
| 130 |
* After incrementing the choice count, the code returns an |
| 131 |
:class:`~django.http.HttpResponseRedirect` rather than a normal |
| 132 |
:class:`~django.http.HttpResponse`. |
| 133 |
:class:`~django.http.HttpResponseRedirect` takes a single argument: the |
| 134 |
URL to which the user will be redirected (see the following point for how |
| 135 |
we construct the URL in this case). |
| 136 |
|
| 137 |
As the Python comment above points out, you should always return an |
| 138 |
:class:`~django.http.HttpResponseRedirect` after successfully dealing with |
| 139 |
POST data. This tip isn't specific to Django; it's good web development |
| 140 |
practice in general. |
| 141 |
|
| 142 |
* We are using the :func:`~django.urls.reverse` function in the |
| 143 |
:class:`~django.http.HttpResponseRedirect` constructor in this example. |
| 144 |
This function helps avoid having to hardcode a URL in the view function. |
| 145 |
It is given the name of the view that we want to pass control to and the |
| 146 |
variable portion of the URL pattern that points to that view. In this |
| 147 |
case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`, |
| 148 |
this :func:`~django.urls.reverse` call will return a string like |
| 149 |
:: |
| 150 |
|
| 151 |
"/polls/3/results/" |
| 152 |
|
| 153 |
where the ``3`` is the value of ``question.id``. This redirected URL will |
| 154 |
then call the ``'results'`` view to display the final page. |
| 155 |
|
| 156 |
As mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an |
| 157 |
:class:`~django.http.HttpRequest` object. For more on |
| 158 |
:class:`~django.http.HttpRequest` objects, see the :doc:`request and |
| 159 |
response documentation </ref/request-response>`. |
| 160 |
|
| 161 |
After somebody votes in a question, the ``vote()`` view redirects to the results |
| 162 |
page for the question. Let's write that view: |
| 163 |
|
| 164 |
.. code-block:: python |
| 165 |
:caption: ``polls/views.py`` |
| 166 |
|
| 167 |
from django.shortcuts import get_object_or_404, render |
| 168 |
|
| 169 |
|
| 170 |
def results(request, question_id): |
| 171 |
question = get_object_or_404(Question, pk=question_id) |
| 172 |
return render(request, "polls/results.html", {"question": question}) |
| 173 |
|
| 174 |
This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3 |
| 175 |
</intro/tutorial03>`. The only difference is the template name. We'll fix this |
| 176 |
redundancy later. |
| 177 |
|
| 178 |
Now, create a ``polls/results.html`` template: |
| 179 |
|
| 180 |
.. code-block:: html+django |
| 181 |
:caption: ``polls/templates/polls/results.html`` |
| 182 |
|
| 183 |
<h1>{{ question.question_text }}</h1> |
| 184 |
|
| 185 |
<ul> |
| 186 |
{% for choice in question.choice_set.all %} |
| 187 |
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> |
| 188 |
{% endfor %} |
| 189 |
</ul> |
| 190 |
|
| 191 |
<a href="{% url 'polls:detail' question.id %}">Vote again?</a> |
| 192 |
|
| 193 |
Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a |
| 194 |
results page that gets updated each time you vote. If you submit the form |
| 195 |
without having chosen a choice, you should see the error message. |
| 196 |
|
| 197 |
Use generic views: Less code is better |
| 198 |
====================================== |
| 199 |
|
| 200 |
The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()`` |
| 201 |
views are very short -- and, as mentioned above, redundant. The ``index()`` |
| 202 |
view, which displays a list of polls, is similar. |
| 203 |
|
| 204 |
These views represent a common case of basic web development: getting data from |
| 205 |
the database according to a parameter passed in the URL, loading a template and |
| 206 |
returning the rendered template. Because this is so common, Django provides a |
| 207 |
shortcut, called the "generic views" system. |
| 208 |
|
| 209 |
Generic views abstract common patterns to the point where you don't even need to |
| 210 |
write Python code to write an app. For example, the |
| 211 |
:class:`~django.views.generic.list.ListView` and |
| 212 |
:class:`~django.views.generic.detail.DetailView` generic views |
| 213 |
abstract the concepts of "display a list of objects" and |
| 214 |
"display a detail page for a particular type of object" respectively. |
| 215 |
|
| 216 |
Let's convert our poll app to use the generic views system, so we can delete a |
| 217 |
bunch of our own code. We'll have to take a few steps to make the conversion. |
| 218 |
We will: |
| 219 |
|
| 220 |
#. Convert the URLconf. |
| 221 |
|
| 222 |
#. Delete some of the old, unneeded views. |
| 223 |
|
| 224 |
#. Introduce new views based on Django's generic views. |
| 225 |
|
| 226 |
Read on for details. |
| 227 |
|
| 228 |
.. admonition:: Why the code-shuffle? |
| 229 |
|
| 230 |
Generally, when writing a Django app, you'll evaluate whether generic views |
| 231 |
are a good fit for your problem, and you'll use them from the beginning, |
| 232 |
rather than refactoring your code halfway through. But this tutorial |
| 233 |
intentionally has focused on writing the views "the hard way" until now, to |
| 234 |
focus on core concepts. |
| 235 |
|
| 236 |
You should know basic math before you start using a calculator. |
| 237 |
|
| 238 |
Amend URLconf |
| 239 |
------------- |
| 240 |
|
| 241 |
First, open the ``polls/urls.py`` URLconf and change it like so: |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
:caption: ``polls/urls.py`` |
| 245 |
|
| 246 |
from django.urls import path |
| 247 |
|
| 248 |
from . import views |
| 249 |
|
| 250 |
app_name = "polls" |
| 251 |
urlpatterns = [ |
| 252 |
path("", views.IndexView.as_view(), name="index"), |
| 253 |
path("<int:pk>/", views.DetailView.as_view(), name="detail"), |
| 254 |
path("<int:pk>/results/", views.ResultsView.as_view(), name="results"), |
| 255 |
path("<int:question_id>/vote/", views.vote, name="vote"), |
| 256 |
] |
| 257 |
|
| 258 |
Note that the name of the matched pattern in the path strings of the second and |
| 259 |
third patterns has changed from ``<question_id>`` to ``<pk>``. This is |
| 260 |
necessary because we'll use the |
| 261 |
:class:`~django.views.generic.detail.DetailView` generic view to replace our |
| 262 |
``detail()`` and ``results()`` views, and it expects the primary key value |
| 263 |
captured from the URL to be called ``"pk"``. |
| 264 |
|
| 265 |
Amend views |
| 266 |
----------- |
| 267 |
|
| 268 |
Next, we're going to remove our old ``index``, ``detail``, and ``results`` |
| 269 |
views and use Django's generic views instead. To do so, open the |
| 270 |
``polls/views.py`` file and change it like so: |
| 271 |
|
| 272 |
.. code-block:: python |
| 273 |
:caption: ``polls/views.py`` |
| 274 |
|
| 275 |
from django.db.models import F |
| 276 |
from django.http import HttpResponseRedirect |
| 277 |
from django.shortcuts import get_object_or_404, render |
| 278 |
from django.urls import reverse |
| 279 |
from django.views import generic |
| 280 |
|
| 281 |
from .models import Choice, Question |
| 282 |
|
| 283 |
|
| 284 |
class IndexView(generic.ListView): |
| 285 |
template_name = "polls/index.html" |
| 286 |
context_object_name = "latest_question_list" |
| 287 |
|
| 288 |
def get_queryset(self): |
| 289 |
"""Return the last five published questions.""" |
| 290 |
return Question.objects.order_by("-pub_date")[:5] |
| 291 |
|
| 292 |
|
| 293 |
class DetailView(generic.DetailView): |
| 294 |
model = Question |
| 295 |
template_name = "polls/detail.html" |
| 296 |
|
| 297 |
|
| 298 |
class ResultsView(generic.DetailView): |
| 299 |
model = Question |
| 300 |
template_name = "polls/results.html" |
| 301 |
|
| 302 |
|
| 303 |
def vote(request, question_id): |
| 304 |
# same as above, no changes needed. |
| 305 |
... |
| 306 |
|
| 307 |
Each generic view needs to know what model it will be acting upon. This is |
| 308 |
provided using either the ``model`` attribute (in this example, ``model = |
| 309 |
Question`` for ``DetailView`` and ``ResultsView``) or by defining the |
| 310 |
:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method (as |
| 311 |
shown in ``IndexView``). |
| 312 |
|
| 313 |
By default, the :class:`~django.views.generic.detail.DetailView` generic |
| 314 |
view uses a template called ``<app name>/<model name>_detail.html``. |
| 315 |
In our case, it would use the template ``"polls/question_detail.html"``. The |
| 316 |
``template_name`` attribute is used to tell Django to use a specific |
| 317 |
template name instead of the autogenerated default template name. We |
| 318 |
also specify the ``template_name`` for the ``results`` list view -- |
| 319 |
this ensures that the results view and the detail view have a |
| 320 |
different appearance when rendered, even though they're both a |
| 321 |
:class:`~django.views.generic.detail.DetailView` behind the scenes. |
| 322 |
|
| 323 |
Similarly, the :class:`~django.views.generic.list.ListView` generic |
| 324 |
view uses a default template called ``<app name>/<model |
| 325 |
name>_list.html``; we use ``template_name`` to tell |
| 326 |
:class:`~django.views.generic.list.ListView` to use our existing |
| 327 |
``"polls/index.html"`` template. |
| 328 |
|
| 329 |
In previous parts of the tutorial, the templates have been provided |
| 330 |
with a context that contains the ``question`` and ``latest_question_list`` |
| 331 |
context variables. For ``DetailView`` the ``question`` variable is provided |
| 332 |
automatically -- since we're using a Django model (``Question``), Django |
| 333 |
is able to determine an appropriate name for the context variable. |
| 334 |
However, for ListView, the automatically generated context variable is |
| 335 |
``question_list``. To override this we provide the ``context_object_name`` |
| 336 |
attribute, specifying that we want to use ``latest_question_list`` instead. |
| 337 |
As an alternative approach, you could change your templates to match |
| 338 |
the new default context variables -- but it's a lot easier to tell Django to |
| 339 |
use the variable you want. |
| 340 |
|
| 341 |
Run the server, and use your new polling app based on generic views. |
| 342 |
|
| 343 |
For full details on generic views, see the :doc:`generic views documentation |
| 344 |
</topics/class-based-views/index>`. |
| 345 |
|
| 346 |
When you're comfortable with forms and generic views, read :doc:`part 5 of this |
| 347 |
tutorial</intro/tutorial05>` to learn about testing our polls app. |