tutorial04.txt 15 KB

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