tutorial04.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. =====================================
  2. Writing your first Django app, part 4
  3. =====================================
  4. This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're
  5. continuing the Web-poll application and will focus on simple form processing and
  6. cutting down our code.
  7. Write a simple form
  8. ===================
  9. Let's update our poll detail template ("polls/detail.html") from the last
  10. tutorial, so that the template contains an HTML ``<form>`` element:
  11. .. code-block:: html+django
  12. <h1>{{ poll.question }}</h1>
  13. {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
  14. <form action="{% url 'polls:vote' poll.id %}" method="post">
  15. {% csrf_token %}
  16. {% for choice in poll.choice_set.all %}
  17. <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
  18. <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
  19. {% endfor %}
  20. <input type="submit" value="Vote" />
  21. </form>
  22. A quick rundown:
  23. * The above template displays a radio button for each poll choice. The
  24. ``value`` of each radio button is the associated poll choice's ID. The
  25. ``name`` of each radio button is ``"choice"``. That means, when somebody
  26. selects one of the radio buttons and submits the form, it'll send the
  27. POST data ``choice=3``. This is the basic concept of HTML forms.
  28. * We set the form's ``action`` to ``{% url 'polls:vote' poll.id %}``, and we
  29. set ``method="post"``. Using ``method="post"`` (as opposed to
  30. ``method="get"``) is very important, because the act of submitting this
  31. form will alter data server-side. Whenever you create a form that alters
  32. data server-side, use ``method="post"``. This tip isn't specific to
  33. Django; it's just good Web development practice.
  34. * ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone
  35. through its loop
  36. * Since we're creating a POST form (which can have the effect of modifying
  37. data), we need to worry about Cross Site Request Forgeries.
  38. Thankfully, you don't have to worry too hard, because Django comes with
  39. a very easy-to-use system for protecting against it. In short, all POST
  40. forms that are targeted at internal URLs should use the
  41. :ttag:`{% csrf_token %}<csrf_token>` template tag.
  42. Now, let's create a Django view that handles the submitted data and does
  43. something with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we
  44. created a URLconf for the polls application that includes this line::
  45. url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
  46. We also created a dummy implementation of the ``vote()`` function. Let's
  47. create a real version. Add the following to ``polls/views.py``::
  48. from django.shortcuts import get_object_or_404, render
  49. from django.http import HttpResponseRedirect, HttpResponse
  50. from django.core.urlresolvers import reverse
  51. from polls.models import Choice, Poll
  52. # ...
  53. def vote(request, poll_id):
  54. p = get_object_or_404(Poll, pk=poll_id)
  55. try:
  56. selected_choice = p.choice_set.get(pk=request.POST['choice'])
  57. except (KeyError, Choice.DoesNotExist):
  58. # Redisplay the poll voting form.
  59. return render(request, 'polls/detail.html', {
  60. 'poll': p,
  61. 'error_message': "You didn't select a choice.",
  62. })
  63. else:
  64. selected_choice.votes += 1
  65. selected_choice.save()
  66. # Always return an HttpResponseRedirect after successfully dealing
  67. # with POST data. This prevents data from being posted twice if a
  68. # user hits the Back button.
  69. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
  70. This code includes a few things we haven't covered yet in this tutorial:
  71. * :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
  72. object that lets you access submitted data by key name. In this case,
  73. ``request.POST['choice']`` returns the ID of the selected choice, as a
  74. string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
  75. always strings.
  76. Note that Django also provides :attr:`request.GET
  77. <django.http.HttpRequest.GET>` for accessing GET data in the same way --
  78. but we're explicitly using :attr:`request.POST
  79. <django.http.HttpRequest.POST>` in our code, to ensure that data is only
  80. altered via a POST call.
  81. * ``request.POST['choice']`` will raise :exc:`~exceptions.KeyError` if
  82. ``choice`` wasn't provided in POST data. The above code checks for
  83. :exc:`~exceptions.KeyError` and redisplays the poll form with an error
  84. message if ``choice`` isn't given.
  85. * After incrementing the choice count, the code returns an
  86. :class:`~django.http.HttpResponseRedirect` rather than a normal
  87. :class:`~django.http.HttpResponse`.
  88. :class:`~django.http.HttpResponseRedirect` takes a single argument: the
  89. URL to which the user will be redirected (see the following point for how
  90. we construct the URL in this case).
  91. As the Python comment above points out, you should always return an
  92. :class:`~django.http.HttpResponseRedirect` after successfully dealing with
  93. POST data. This tip isn't specific to Django; it's just good Web
  94. development practice.
  95. * We are using the :func:`~django.core.urlresolvers.reverse` function in the
  96. :class:`~django.http.HttpResponseRedirect` constructor in this example.
  97. This function helps avoid having to hardcode a URL in the view function.
  98. It is given the name of the view that we want to pass control to and the
  99. variable portion of the URL pattern that points to that view. In this
  100. case, using the URLconf we set up in Tutorial 3, this
  101. :func:`~django.core.urlresolvers.reverse` call will return a string like
  102. ::
  103. '/polls/3/results/'
  104. ... where the ``3`` is the value of ``p.id``. This redirected URL will
  105. then call the ``'results'`` view to display the final page.
  106. As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
  107. object. For more on :class:`~django.http.HttpRequest` objects, see the
  108. :doc:`request and response documentation </ref/request-response>`.
  109. After somebody votes in a poll, the ``vote()`` view redirects to the results
  110. page for the poll. Let's write that view::
  111. def results(request, poll_id):
  112. poll = get_object_or_404(Poll, pk=poll_id)
  113. return render(request, 'polls/results.html', {'poll': poll})
  114. This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3
  115. </intro/tutorial03>`. The only difference is the template name. We'll fix this
  116. redundancy later.
  117. Now, create a ``polls/results.html`` template:
  118. .. code-block:: html+django
  119. <h1>{{ poll.question }}</h1>
  120. <ul>
  121. {% for choice in poll.choice_set.all %}
  122. <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
  123. {% endfor %}
  124. </ul>
  125. <a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
  126. Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a
  127. results page that gets updated each time you vote. If you submit the form
  128. without having chosen a choice, you should see the error message.
  129. Use generic views: Less code is better
  130. ======================================
  131. The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
  132. views are stupidly simple -- and, as mentioned above, redundant. The ``index()``
  133. view (also from Tutorial 3), which displays a list of polls, is similar.
  134. These views represent a common case of basic Web development: getting data from
  135. the database according to a parameter passed in the URL, loading a template and
  136. returning the rendered template. Because this is so common, Django provides a
  137. shortcut, called the "generic views" system.
  138. Generic views abstract common patterns to the point where you don't even need
  139. to write Python code to write an app.
  140. Let's convert our poll app to use the generic views system, so we can delete a
  141. bunch of our own code. We'll just have to take a few steps to make the
  142. conversion. We will:
  143. 1. Convert the URLconf.
  144. 2. Delete some of the old, unneeded views.
  145. 3. Fix up URL handling for the new views.
  146. Read on for details.
  147. .. admonition:: Why the code-shuffle?
  148. Generally, when writing a Django app, you'll evaluate whether generic views
  149. are a good fit for your problem, and you'll use them from the beginning,
  150. rather than refactoring your code halfway through. But this tutorial
  151. intentionally has focused on writing the views "the hard way" until now, to
  152. focus on core concepts.
  153. You should know basic math before you start using a calculator.
  154. Amend URLconf
  155. -------------
  156. First, open the ``polls/urls.py`` URLconf and change it like so::
  157. from django.conf.urls import patterns, url
  158. from django.views.generic import DetailView, ListView
  159. from polls.models import Poll
  160. urlpatterns = patterns('',
  161. url(r'^$',
  162. ListView.as_view(
  163. queryset=Poll.objects.order_by('-pub_date')[:5],
  164. context_object_name='latest_poll_list',
  165. template_name='polls/index.html'),
  166. name='index'),
  167. url(r'^(?P<pk>\d+)/$',
  168. DetailView.as_view(
  169. model=Poll,
  170. template_name='polls/detail.html'),
  171. name='detail'),
  172. url(r'^(?P<pk>\d+)/results/$',
  173. DetailView.as_view(
  174. model=Poll,
  175. template_name='polls/results.html'),
  176. name='results'),
  177. url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='vote'),
  178. )
  179. Amend views
  180. -----------
  181. We're using two generic views here:
  182. :class:`~django.views.generic.list.ListView` and
  183. :class:`~django.views.generic.detail.DetailView`. Respectively, those
  184. two views abstract the concepts of "display a list of objects" and
  185. "display a detail page for a particular type of object."
  186. * Each generic view needs to know what model it will be acting
  187. upon. This is provided using the ``model`` parameter.
  188. * The :class:`~django.views.generic.detail.DetailView` generic view
  189. expects the primary key value captured from the URL to be called
  190. ``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic
  191. views.
  192. By default, the :class:`~django.views.generic.detail.DetailView` generic
  193. view uses a template called ``<app name>/<model name>_detail.html``.
  194. In our case, it'll use the template ``"polls/poll_detail.html"``. The
  195. ``template_name`` argument is used to tell Django to use a specific
  196. template name instead of the autogenerated default template name. We
  197. also specify the ``template_name`` for the ``results`` list view --
  198. this ensures that the results view and the detail view have a
  199. different appearance when rendered, even though they're both a
  200. :class:`~django.views.generic.detail.DetailView` behind the scenes.
  201. Similarly, the :class:`~django.views.generic.list.ListView` generic
  202. view uses a default template called ``<app name>/<model
  203. name>_list.html``; we use ``template_name`` to tell
  204. :class:`~django.views.generic.list.ListView` to use our existing
  205. ``"polls/index.html"`` template.
  206. In previous parts of the tutorial, the templates have been provided
  207. with a context that contains the ``poll`` and ``latest_poll_list``
  208. context variables. For ``DetailView`` the ``poll`` variable is provided
  209. automatically -- since we're using a Django model (``Poll``), Django
  210. is able to determine an appropriate name for the context variable.
  211. However, for ListView, the automatically generated context variable is
  212. ``poll_list``. To override this we provide the ``context_object_name``
  213. option, specifying that we want to use ``latest_poll_list`` instead.
  214. As an alternative approach, you could change your templates to match
  215. the new default context variables -- but it's a lot easier to just
  216. tell Django to use the variable you want.
  217. You can now delete the ``index()``, ``detail()`` and ``results()`` views from
  218. ``polls/views.py``. We don't need them anymore -- they have been replaced by
  219. generic views. You can also delete the import for ``HttpResponse``, which is no
  220. longer required.
  221. Run the server, and use your new polling app based on generic views.
  222. For full details on generic views, see the :doc:`generic views documentation
  223. </topics/class-based-views/index>`.
  224. When you're comfortable with forms and generic views, read :doc:`part 5 of this
  225. tutorial</intro/tutorial05>` to learn about testing our polls app.