tutorial04.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. .. _intro-tutorial04:
  2. =====================================
  3. Writing your first Django app, part 4
  4. =====================================
  5. This tutorial begins where :ref:`Tutorial 3 <intro-tutorial03>` left off. We're
  6. continuing the Web-poll application and will focus on simple form processing and
  7. cutting down our code.
  8. Write a simple form
  9. ===================
  10. Let's update our poll detail template ("polls/detail.html") from the last
  11. tutorial, so that the template contains an HTML ``<form>`` element:
  12. .. code-block:: html+django
  13. <h1>{{ poll.question }}</h1>
  14. {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
  15. <form action="/polls/{{ poll.id }}/vote/" method="post">
  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 }}</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 ``/polls/{{ poll.id }}/vote/``, 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. Now, let's create a Django view that handles the submitted data and does
  37. something with it. Remember, in :ref:`Tutorial 3 <intro-tutorial03>`, we created
  38. a URLconf for the polls application that includes this line::
  39. (r'^(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
  40. So let's create a ``vote()`` function in ``mysite/polls/views.py``::
  41. from django.shortcuts import get_object_or_404, render_to_response
  42. from django.http import HttpResponseRedirect
  43. from django.core.urlresolvers import reverse
  44. from mysite.polls.models import Choice, Poll
  45. # ...
  46. def vote(request, poll_id):
  47. p = get_object_or_404(Poll, pk=poll_id)
  48. try:
  49. selected_choice = p.choice_set.get(pk=request.POST['choice'])
  50. except (KeyError, Choice.DoesNotExist):
  51. # Redisplay the poll voting form.
  52. return render_to_response('polls/detail.html', {
  53. 'poll': p,
  54. 'error_message': "You didn't select a choice.",
  55. })
  56. else:
  57. selected_choice.votes += 1
  58. selected_choice.save()
  59. # Always return an HttpResponseRedirect after successfully dealing
  60. # with POST data. This prevents data from being posted twice if a
  61. # user hits the Back button.
  62. return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
  63. This code includes a few things we haven't covered yet in this tutorial:
  64. * :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
  65. object that lets you access submitted data by key name. In this case,
  66. ``request.POST['choice']`` returns the ID of the selected choice, as a
  67. string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
  68. always strings.
  69. Note that Django also provides :attr:`request.GET
  70. <django.http.HttpRequest.GET>` for accessing GET data in the same way --
  71. but we're explicitly using :attr:`request.POST
  72. <django.http.HttpRequest.POST>` in our code, to ensure that data is only
  73. altered via a POST call.
  74. * ``request.POST['choice']`` will raise :exc:`KeyError` if ``choice`` wasn't
  75. provided in POST data. The above code checks for :exc:`KeyError` and
  76. redisplays the poll form with an error message if ``choice`` isn't given.
  77. * After incrementing the choice count, the code returns an
  78. :class:`~django.http.HttpResponseRedirect` rather than a normal
  79. :class:`~django.http.HttpResponse`.
  80. :class:`~django.http.HttpResponseRedirect` takes a single argument: the
  81. URL to which the user will be redirected (see the following point for how
  82. we construct the URL in this case).
  83. As the Python comment above points out, you should always return an
  84. :class:`~django.http.HttpResponseRedirect` after successfully dealing with
  85. POST data. This tip isn't specific to Django; it's just good Web
  86. development practice.
  87. * We are using the :func:`~django.core.urlresolvers.reverse` function in the
  88. :class:`~django.http.HttpResponseRedirect` constructor in this example.
  89. This function helps avoid having to hardcode a URL in the view function.
  90. It is given the name of the view that we want to pass control to and the
  91. variable portion of the URL pattern that points to that view. In this
  92. case, using the URLConf we set up in Tutorial 3, this
  93. :func:`~django.core.urlresolvers.reverse` call will return a string like
  94. ::
  95. '/polls/3/results/'
  96. ... where the ``3`` is the value of ``p.id``. This redirected URL will
  97. then call the ``'results'`` view to display the final page. Note that you
  98. need to use the full name of the view here (including the prefix).
  99. As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
  100. object. For more on :class:`~django.http.HttpRequest` objects, see the
  101. :ref:`request and response documentation <ref-request-response>`.
  102. After somebody votes in a poll, the ``vote()`` view redirects to the results
  103. page for the poll. Let's write that view::
  104. def results(request, poll_id):
  105. p = get_object_or_404(Poll, pk=poll_id)
  106. return render_to_response('polls/results.html', {'poll': p})
  107. This is almost exactly the same as the ``detail()`` view from :ref:`Tutorial 3
  108. <intro-tutorial03>`. The only difference is the template name. We'll fix this
  109. redundancy later.
  110. Now, create a ``results.html`` template:
  111. .. code-block:: html+django
  112. <h1>{{ poll.question }}</h1>
  113. <ul>
  114. {% for choice in poll.choice_set.all %}
  115. <li>{{ choice.choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
  116. {% endfor %}
  117. </ul>
  118. Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a
  119. results page that gets updated each time you vote. If you submit the form
  120. without having chosen a choice, you should see the error message.
  121. Use generic views: Less code is better
  122. ======================================
  123. The ``detail()`` (from :ref:`Tutorial 3 <intro-tutorial03>`) and ``results()``
  124. views are stupidly simple -- and, as mentioned above, redundant. The ``index()``
  125. view (also from Tutorial 3), which displays a list of polls, is similar.
  126. These views represent a common case of basic Web development: getting data from
  127. the database according to a parameter passed in the URL, loading a template and
  128. returning the rendered template. Because this is so common, Django provides a
  129. shortcut, called the "generic views" system.
  130. Generic views abstract common patterns to the point where you don't even need
  131. to write Python code to write an app.
  132. Let's convert our poll app to use the generic views system, so we can delete a
  133. bunch of our own code. We'll just have to take a few steps to make the
  134. conversion.
  135. .. admonition:: Why the code-shuffle?
  136. Generally, when writing a Django app, you'll evaluate whether generic views
  137. are a good fit for your problem, and you'll use them from the beginning,
  138. rather than refactoring your code halfway through. But this tutorial
  139. intentionally has focused on writing the views "the hard way" until now, to
  140. focus on core concepts.
  141. You should know basic math before you start using a calculator.
  142. First, open the ``polls/urls.py`` URLconf. It looks like this, according to the
  143. tutorial so far::
  144. from django.conf.urls.defaults import *
  145. urlpatterns = patterns('mysite.polls.views',
  146. (r'^$', 'index'),
  147. (r'^(?P<poll_id>\d+)/$', 'detail'),
  148. (r'^(?P<poll_id>\d+)/results/$', 'results'),
  149. (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
  150. )
  151. Change it like so::
  152. from django.conf.urls.defaults import *
  153. from mysite.polls.models import Poll
  154. info_dict = {
  155. 'queryset': Poll.objects.all(),
  156. }
  157. urlpatterns = patterns('',
  158. (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
  159. (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
  160. url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
  161. (r'^(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
  162. )
  163. We're using two generic views here:
  164. :func:`~django.views.generic.list_detail.object_list` and
  165. :func:`~django.views.generic.list_detail.object_detail`. Respectively, those two
  166. views abstract the concepts of "display a list of objects" and "display a detail
  167. page for a particular type of object."
  168. * Each generic view needs to know what data it will be acting upon. This
  169. data is provided in a dictionary. The ``queryset`` key in this dictionary
  170. points to the list of objects to be manipulated by the generic view.
  171. * The :func:`~django.views.generic.list_detail.object_detail` generic view
  172. expects the ID value captured from the URL to be called ``"object_id"``,
  173. so we've changed ``poll_id`` to ``object_id`` for the generic views.
  174. * We've added a name, ``poll_results``, to the results view so that we have
  175. a way to refer to its URL later on (see the documentation about
  176. :ref:`naming URL patterns <naming-url-patterns>` for information). We're
  177. also using the :func:`~django.conf.urls.default.url` function from
  178. :mod:`django.conf.urls.defaults` here. It's a good habit to use
  179. :func:`~django.conf.urls.defaults.url` when you are providing a pattern
  180. name like this.
  181. By default, the :func:`~django.views.generic.list_detail.object_detail` generic
  182. view uses a template called ``<app name>/<model name>_detail.html``. In our
  183. case, it'll use the template ``"polls/poll_detail.html"``. Thus, rename your
  184. ``polls/detail.html`` template to ``polls/poll_detail.html``, and change the
  185. :func:`~django.shortcuts.render_to_response` line in ``vote()``.
  186. Similarly, the :func:`~django.views.generic.list_detail.object_list` generic
  187. view uses a template called ``<app name>/<model name>_list.html``. Thus, rename
  188. ``polls/index.html`` to ``polls/poll_list.html``.
  189. Because we have more than one entry in the URLconf that uses
  190. :func:`~django.views.generic.list_detail.object_detail` for the polls app, we
  191. manually specify a template name for the results view:
  192. ``template_name='polls/results.html'``. Otherwise, both views would use the same
  193. template. Note that we use ``dict()`` to return an altered dictionary in place.
  194. .. note:: :meth:`django.db.models.QuerySet.all` is lazy
  195. It might look a little frightening to see ``Poll.objects.all()`` being used
  196. in a detail view which only needs one ``Poll`` object, but don't worry;
  197. ``Poll.objects.all()`` is actually a special object called a
  198. :class:`~django.db.models.QuerySet`, which is "lazy" and doesn't hit your
  199. database until it absolutely has to. By the time the database query happens,
  200. the :func:`~django.views.generic.list_detail.object_detail` generic view
  201. will have narrowed its scope down to a single object, so the eventual query
  202. will only select one row from the database.
  203. If you'd like to know more about how that works, The Django database API
  204. documentation :ref:`explains the lazy nature of QuerySet objects
  205. <querysets-are-lazy>`.
  206. In previous parts of the tutorial, the templates have been provided with a
  207. context that contains the ``poll`` and ``latest_poll_list`` context variables.
  208. However, the generic views provide the variables ``object`` and ``object_list``
  209. as context. Therefore, you need to change your templates to match the new
  210. context variables. Go through your templates, and modify any reference to
  211. ``latest_poll_list`` to ``object_list``, and change any reference to ``poll``
  212. to ``object``.
  213. You can now delete the ``index()``, ``detail()`` and ``results()`` views
  214. from ``polls/views.py``. We don't need them anymore -- they have been replaced
  215. by generic views.
  216. The ``vote()`` view is still required. However, it must be modified to match the
  217. new context variables. In the :func:`~django.shortcuts.render_to_response` call,
  218. rename the ``poll`` context variable to ``object``.
  219. The last thing to do is fix the URL handling to account for the use of generic
  220. views. In the vote view above, we used the
  221. :func:`~django.core.urlresolvers.reverse` function to avoid hard-coding our
  222. URLs. Now that we've switched to a generic view, we'll need to change the
  223. :func:`~django.core.urlresolvers.reverse` call to point back to our new generic
  224. view. We can't simply use the view function anymore -- generic views can be (and
  225. are) used multiple times -- but we can use the name we've given::
  226. return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
  227. Run the server, and use your new polling app based on generic views.
  228. For full details on generic views, see the :ref:`generic views documentation
  229. <topics-http-generic-views>`.
  230. Coming soon
  231. ===========
  232. The tutorial ends here for the time being. Future installments of the tutorial
  233. will cover:
  234. * Advanced form processing
  235. * Using the RSS framework
  236. * Using the cache framework
  237. * Using the comments framework
  238. * Advanced admin features: Permissions
  239. * Advanced admin features: Custom JavaScript
  240. In the meantime, you might want to check out some pointers on :ref:`where to go
  241. from here <intro-whatsnext>`