tutorial04.txt 14 KB

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