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.http import HttpResponse, HttpResponseRedirect
    
  78.     from django.shortcuts import get_object_or_404, render
    
  79.     from django.urls import reverse
    
  80. 
    
  81.     from .models import Choice, Question
    
  82.     # ...
    
  83.     def vote(request, question_id):
    
  84.         question = get_object_or_404(Question, pk=question_id)
    
  85.         try:
    
  86.             selected_choice = question.choice_set.get(pk=request.POST['choice'])
    
  87.         except (KeyError, Choice.DoesNotExist):
    
  88.             # Redisplay the question voting form.
    
  89.             return render(request, 'polls/detail.html', {
    
  90.                 'question': question,
    
  91.                 'error_message': "You didn't select a choice.",
    
  92.             })
    
  93.         else:
    
  94.             selected_choice.votes += 1
    
  95.             selected_choice.save()
    
  96.             # Always return an HttpResponseRedirect after successfully dealing
    
  97.             # with POST data. This prevents data from being posted twice if a
    
  98.             # user hits the Back button.
    
  99.             return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
    
  100. 
    
  101. This code includes a few things we haven't covered yet in this tutorial:
    
  102. 
    
  103. * :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
    
  104.   object that lets you access submitted data by key name. In this case,
    
  105.   ``request.POST['choice']`` returns the ID of the selected choice, as a
    
  106.   string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
    
  107.   always strings.
    
  108. 
    
  109.   Note that Django also provides :attr:`request.GET
    
  110.   <django.http.HttpRequest.GET>` for accessing GET data in the same way --
    
  111.   but we're explicitly using :attr:`request.POST
    
  112.   <django.http.HttpRequest.POST>` in our code, to ensure that data is only
    
  113.   altered via a POST call.
    
  114. 
    
  115. * ``request.POST['choice']`` will raise :exc:`KeyError` if
    
  116.   ``choice`` wasn't provided in POST data. The above code checks for
    
  117.   :exc:`KeyError` and redisplays the question form with an error
    
  118.   message if ``choice`` isn't given.
    
  119. 
    
  120. * After incrementing the choice count, the code returns an
    
  121.   :class:`~django.http.HttpResponseRedirect` rather than a normal
    
  122.   :class:`~django.http.HttpResponse`.
    
  123.   :class:`~django.http.HttpResponseRedirect` takes a single argument: the
    
  124.   URL to which the user will be redirected (see the following point for how
    
  125.   we construct the URL in this case).
    
  126. 
    
  127.   As the Python comment above points out, you should always return an
    
  128.   :class:`~django.http.HttpResponseRedirect` after successfully dealing with
    
  129.   POST data. This tip isn't specific to Django; it's good web development
    
  130.   practice in general.
    
  131. 
    
  132. * We are using the :func:`~django.urls.reverse` function in the
    
  133.   :class:`~django.http.HttpResponseRedirect` constructor in this example.
    
  134.   This function helps avoid having to hardcode a URL in the view function.
    
  135.   It is given the name of the view that we want to pass control to and the
    
  136.   variable portion of the URL pattern that points to that view. In this
    
  137.   case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`,
    
  138.   this :func:`~django.urls.reverse` call will return a string like
    
  139.   ::
    
  140. 
    
  141.     '/polls/3/results/'
    
  142. 
    
  143.   where the ``3`` is the value of ``question.id``. This redirected URL will
    
  144.   then call the ``'results'`` view to display the final page.
    
  145. 
    
  146. As mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an
    
  147. :class:`~django.http.HttpRequest` object. For more on
    
  148. :class:`~django.http.HttpRequest` objects, see the :doc:`request and
    
  149. response documentation </ref/request-response>`.
    
  150. 
    
  151. After somebody votes in a question, the ``vote()`` view redirects to the results
    
  152. page for the question. Let's write that view:
    
  153. 
    
  154. .. code-block:: python
    
  155.     :caption: ``polls/views.py``
    
  156. 
    
  157.     from django.shortcuts import get_object_or_404, render
    
  158. 
    
  159. 
    
  160.     def results(request, question_id):
    
  161.         question = get_object_or_404(Question, pk=question_id)
    
  162.         return render(request, 'polls/results.html', {'question': question})
    
  163. 
    
  164. This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3
    
  165. </intro/tutorial03>`. The only difference is the template name. We'll fix this
    
  166. redundancy later.
    
  167. 
    
  168. Now, create a ``polls/results.html`` template:
    
  169. 
    
  170. .. code-block:: html+django
    
  171.     :caption: ``polls/templates/polls/results.html``
    
  172. 
    
  173.     <h1>{{ question.question_text }}</h1>
    
  174. 
    
  175.     <ul>
    
  176.     {% for choice in question.choice_set.all %}
    
  177.         <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
    
  178.     {% endfor %}
    
  179.     </ul>
    
  180. 
    
  181.     <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
    
  182. 
    
  183. Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
    
  184. results page that gets updated each time you vote. If you submit the form
    
  185. without having chosen a choice, you should see the error message.
    
  186. 
    
  187. .. note::
    
  188.     The code for our ``vote()`` view does have a small problem. It first gets
    
  189.     the ``selected_choice`` object from the database, then computes the new
    
  190.     value of ``votes``, and then saves it back to the database. If two users of
    
  191.     your website try to vote at *exactly the same time*, this might go wrong:
    
  192.     The same value, let's say 42, will be retrieved for ``votes``. Then, for
    
  193.     both users the new value of 43 is computed and saved, but 44 would be the
    
  194.     expected value.
    
  195. 
    
  196.     This is called a *race condition*. If you are interested, you can read
    
  197.     :ref:`avoiding-race-conditions-using-f` to learn how you can solve this
    
  198.     issue.
    
  199. 
    
  200. Use generic views: Less code is better
    
  201. ======================================
    
  202. 
    
  203. The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
    
  204. views are very short -- and, as mentioned above, redundant. The ``index()``
    
  205. view, which displays a list of polls, is similar.
    
  206. 
    
  207. These views represent a common case of basic web development: getting data from
    
  208. the database according to a parameter passed in the URL, loading a template and
    
  209. returning the rendered template. Because this is so common, Django provides a
    
  210. shortcut, called the "generic views" system.
    
  211. 
    
  212. Generic views abstract common patterns to the point where you don't even need
    
  213. to write Python code to write an app.
    
  214. 
    
  215. Let's convert our poll app to use the generic views system, so we can delete a
    
  216. bunch of our own code. We'll have to take a few steps to make the conversion.
    
  217. We will:
    
  218. 
    
  219. #. Convert the URLconf.
    
  220. 
    
  221. #. Delete some of the old, unneeded views.
    
  222. 
    
  223. #. Introduce new views based on Django's generic views.
    
  224. 
    
  225. Read on for details.
    
  226. 
    
  227. .. admonition:: Why the code-shuffle?
    
  228. 
    
  229.     Generally, when writing a Django app, you'll evaluate whether generic views
    
  230.     are a good fit for your problem, and you'll use them from the beginning,
    
  231.     rather than refactoring your code halfway through. But this tutorial
    
  232.     intentionally has focused on writing the views "the hard way" until now, to
    
  233.     focus on core concepts.
    
  234. 
    
  235.     You should know basic math before you start using a calculator.
    
  236. 
    
  237. Amend URLconf
    
  238. -------------
    
  239. 
    
  240. First, open the ``polls/urls.py`` URLconf and change it like so:
    
  241. 
    
  242. .. code-block:: python
    
  243.     :caption: ``polls/urls.py``
    
  244. 
    
  245.     from django.urls import path
    
  246. 
    
  247.     from . import views
    
  248. 
    
  249.     app_name = 'polls'
    
  250.     urlpatterns = [
    
  251.         path('', views.IndexView.as_view(), name='index'),
    
  252.         path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    
  253.         path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    
  254.         path('<int:question_id>/vote/', views.vote, name='vote'),
    
  255.     ]
    
  256. 
    
  257. Note that the name of the matched pattern in the path strings of the second and
    
  258. third patterns has changed from ``<question_id>`` to ``<pk>``.
    
  259. 
    
  260. Amend views
    
  261. -----------
    
  262. 
    
  263. Next, we're going to remove our old ``index``, ``detail``, and ``results``
    
  264. views and use Django's generic views instead. To do so, open the
    
  265. ``polls/views.py`` file and change it like so:
    
  266. 
    
  267. .. code-block:: python
    
  268.     :caption: ``polls/views.py``
    
  269. 
    
  270.     from django.http import HttpResponseRedirect
    
  271.     from django.shortcuts import get_object_or_404, render
    
  272.     from django.urls import reverse
    
  273.     from django.views import generic
    
  274. 
    
  275.     from .models import Choice, Question
    
  276. 
    
  277. 
    
  278.     class IndexView(generic.ListView):
    
  279.         template_name = 'polls/index.html'
    
  280.         context_object_name = 'latest_question_list'
    
  281. 
    
  282.         def get_queryset(self):
    
  283.             """Return the last five published questions."""
    
  284.             return Question.objects.order_by('-pub_date')[:5]
    
  285. 
    
  286. 
    
  287.     class DetailView(generic.DetailView):
    
  288.         model = Question
    
  289.         template_name = 'polls/detail.html'
    
  290. 
    
  291. 
    
  292.     class ResultsView(generic.DetailView):
    
  293.         model = Question
    
  294.         template_name = 'polls/results.html'
    
  295. 
    
  296. 
    
  297.     def vote(request, question_id):
    
  298.         ... # same as above, no changes needed.
    
  299. 
    
  300. We're using two generic views here:
    
  301. :class:`~django.views.generic.list.ListView` and
    
  302. :class:`~django.views.generic.detail.DetailView`. Respectively, those
    
  303. two views abstract the concepts of "display a list of objects" and
    
  304. "display a detail page for a particular type of object."
    
  305. 
    
  306. * Each generic view needs to know what model it will be acting
    
  307.   upon. This is provided using the ``model`` attribute.
    
  308. 
    
  309. * The :class:`~django.views.generic.detail.DetailView` generic view
    
  310.   expects the primary key value captured from the URL to be called
    
  311.   ``"pk"``, so we've changed ``question_id`` to ``pk`` for the generic
    
  312.   views.
    
  313. 
    
  314. By default, the :class:`~django.views.generic.detail.DetailView` generic
    
  315. view uses a template called ``<app name>/<model name>_detail.html``.
    
  316. In our case, it would use the template ``"polls/question_detail.html"``. The
    
  317. ``template_name`` attribute is used to tell Django to use a specific
    
  318. template name instead of the autogenerated default template name. We
    
  319. also specify the ``template_name`` for the ``results`` list view --
    
  320. this ensures that the results view and the detail view have a
    
  321. different appearance when rendered, even though they're both a
    
  322. :class:`~django.views.generic.detail.DetailView` behind the scenes.
    
  323. 
    
  324. Similarly, the :class:`~django.views.generic.list.ListView` generic
    
  325. view uses a default template called ``<app name>/<model
    
  326. name>_list.html``; we use ``template_name`` to tell
    
  327. :class:`~django.views.generic.list.ListView` to use our existing
    
  328. ``"polls/index.html"`` template.
    
  329. 
    
  330. In previous parts of the tutorial, the templates have been provided
    
  331. with a context that contains the ``question`` and ``latest_question_list``
    
  332. context variables. For ``DetailView`` the ``question`` variable is provided
    
  333. automatically -- since we're using a Django model (``Question``), Django
    
  334. is able to determine an appropriate name for the context variable.
    
  335. However, for ListView, the automatically generated context variable is
    
  336. ``question_list``. To override this we provide the ``context_object_name``
    
  337. attribute, specifying that we want to use ``latest_question_list`` instead.
    
  338. As an alternative approach, you could change your templates to match
    
  339. the new default context variables -- but it's a lot easier to tell Django to
    
  340. use the variable you want.
    
  341. 
    
  342. Run the server, and use your new polling app based on generic views.
    
  343. 
    
  344. For full details on generic views, see the :doc:`generic views documentation
    
  345. </topics/class-based-views/index>`.
    
  346. 
    
  347. When you're comfortable with forms and generic views, read :doc:`part 5 of this
    
  348. tutorial</intro/tutorial05>` to learn about testing our polls app.