tutorial04.txt 15 KB

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