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 HTML Forms 101.
  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:`KeyError` if ``choice`` wasn't
  82. provided in POST data. The above code checks for :exc:`KeyError` and
  83. redisplays the poll form with an error message if ``choice`` isn't given.
  84. * After incrementing the choice count, the code returns an
  85. :class:`~django.http.HttpResponseRedirect` rather than a normal
  86. :class:`~django.http.HttpResponse`.
  87. :class:`~django.http.HttpResponseRedirect` takes a single argument: the
  88. URL to which the user will be redirected (see the following point for how
  89. we construct the URL in this case).
  90. As the Python comment above points out, you should always return an
  91. :class:`~django.http.HttpResponseRedirect` after successfully dealing with
  92. POST data. This tip isn't specific to Django; it's just good Web
  93. development practice.
  94. * We are using the :func:`~django.core.urlresolvers.reverse` function in the
  95. :class:`~django.http.HttpResponseRedirect` constructor in this example.
  96. This function helps avoid having to hardcode a URL in the view function.
  97. It is given the name of the view that we want to pass control to and the
  98. variable portion of the URL pattern that points to that view. In this
  99. case, using the URLconf we set up in Tutorial 3, this
  100. :func:`~django.core.urlresolvers.reverse` call will return a string like
  101. ::
  102. '/polls/3/results/'
  103. ... where the ``3`` is the value of ``p.id``. This redirected URL will
  104. then call the ``'results'`` view to display the final page.
  105. As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
  106. object. For more on :class:`~django.http.HttpRequest` objects, see the
  107. :doc:`request and response documentation </ref/request-response>`.
  108. After somebody votes in a poll, the ``vote()`` view redirects to the results
  109. page for the poll. Let's write that view::
  110. def results(request, poll_id):
  111. poll = get_object_or_404(Poll, pk=poll_id)
  112. return render(request, 'polls/results.html', {'poll': poll})
  113. This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3
  114. </intro/tutorial03>`. The only difference is the template name. We'll fix this
  115. redundancy later.
  116. Now, create a ``polls/results.html`` template:
  117. .. code-block:: html+django
  118. <h1>{{ poll.question }}</h1>
  119. <ul>
  120. {% for choice in poll.choice_set.all %}
  121. <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
  122. {% endfor %}
  123. </ul>
  124. <a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
  125. Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a
  126. results page that gets updated each time you vote. If you submit the form
  127. without having chosen a choice, you should see the error message.
  128. Use generic views: Less code is better
  129. ======================================
  130. The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
  131. views are stupidly simple -- and, as mentioned above, redundant. The ``index()``
  132. view (also from Tutorial 3), which displays a list of polls, is similar.
  133. These views represent a common case of basic Web development: getting data from
  134. the database according to a parameter passed in the URL, loading a template and
  135. returning the rendered template. Because this is so common, Django provides a
  136. shortcut, called the "generic views" system.
  137. Generic views abstract common patterns to the point where you don't even need
  138. to write Python code to write an app.
  139. Let's convert our poll app to use the generic views system, so we can delete a
  140. bunch of our own code. We'll just have to take a few steps to make the
  141. conversion. We will:
  142. 1. Convert the URLconf.
  143. 2. Delete some of the old, unneeded views.
  144. 3. Fix up URL handling for the new views.
  145. Read on for details.
  146. .. admonition:: Why the code-shuffle?
  147. Generally, when writing a Django app, you'll evaluate whether generic views
  148. are a good fit for your problem, and you'll use them from the beginning,
  149. rather than refactoring your code halfway through. But this tutorial
  150. intentionally has focused on writing the views "the hard way" until now, to
  151. focus on core concepts.
  152. You should know basic math before you start using a calculator.
  153. First, open the ``polls/urls.py`` URLconf and change it like so::
  154. from django.conf.urls import patterns, url
  155. from django.views.generic import DetailView, ListView
  156. from polls.models import Poll
  157. urlpatterns = patterns('',
  158. url(r'^$',
  159. ListView.as_view(
  160. queryset=Poll.objects.order_by('-pub_date')[:5],
  161. context_object_name='latest_poll_list',
  162. template_name='polls/index.html'),
  163. name='index'),
  164. url(r'^(?P<pk>\d+)/$',
  165. DetailView.as_view(
  166. model=Poll,
  167. template_name='polls/detail.html'),
  168. name='detail'),
  169. url(r'^(?P<pk>\d+)/results/$',
  170. DetailView.as_view(
  171. model=Poll,
  172. template_name='polls/results.html'),
  173. name='results'),
  174. url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='vote'),
  175. )
  176. We're using two generic views here:
  177. :class:`~django.views.generic.list.ListView` and
  178. :class:`~django.views.generic.detail.DetailView`. Respectively, those
  179. two views abstract the concepts of "display a list of objects" and
  180. "display a detail page for a particular type of object."
  181. * Each generic view needs to know what model it will be acting
  182. upon. This is provided using the ``model`` parameter.
  183. * The :class:`~django.views.generic.list.DetailView` generic view
  184. expects the primary key value captured from the URL to be called
  185. ``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic
  186. views.
  187. By default, the :class:`~django.views.generic.list.DetailView` generic
  188. view uses a template called ``<app name>/<model name>_detail.html``.
  189. In our case, it'll use the template ``"polls/poll_detail.html"``. The
  190. ``template_name`` argument is used to tell Django to use a specific
  191. template name instead of the autogenerated default template name. We
  192. also specify the ``template_name`` for the ``results`` list view --
  193. this ensures that the results view and the detail view have a
  194. different appearance when rendered, even though they're both a
  195. :class:`~django.views.generic.list.DetailView` behind the scenes.
  196. Similarly, the :class:`~django.views.generic.list.ListView` generic
  197. view uses a default template called ``<app name>/<model
  198. name>_list.html``; we use ``template_name`` to tell
  199. :class:`~django.views.generic.list.ListView` to use our existing
  200. ``"polls/index.html"`` template.
  201. In previous parts of the tutorial, the templates have been provided
  202. with a context that contains the ``poll`` and ``latest_poll_list``
  203. context variables. For DetailView the ``poll`` variable is provided
  204. automatically -- since we're using a Django model (``Poll``), Django
  205. is able to determine an appropriate name for the context variable.
  206. However, for ListView, the automatically generated context variable is
  207. ``poll_list``. To override this we provide the ``context_object_name``
  208. option, specifying that we want to use ``latest_poll_list`` instead.
  209. As an alternative approach, you could change your templates to match
  210. the new default context variables -- but it's a lot easier to just
  211. tell Django to use the variable you want.
  212. You can now delete the ``index()``, ``detail()`` and ``results()``
  213. views from ``polls/views.py``. We don't need them anymore -- they have
  214. been replaced by generic views.
  215. Run the server, and use your new polling app based on generic views.
  216. For full details on generic views, see the :doc:`generic views documentation
  217. </topics/class-based-views/index>`.
  218. What's next?
  219. ============
  220. The beginner tutorial ends here for the time being. In the meantime, you might
  221. want to check out some pointers on :doc:`where to go from here
  222. </intro/whatsnext>`.
  223. If you are familiar with Python packaging and interested in learning how to
  224. turn polls into a "reusable app", check out :doc:`Advanced tutorial: How to
  225. write reusable apps</intro/reusable-apps>`.