tutorial04.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 ``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 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('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('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 django.views.generic import DetailView, ListView
  180. from polls.models import Poll
  181. info_dict = {
  182. 'queryset': Poll.objects.all(),
  183. }
  184. urlpatterns = patterns('',
  185. (r'^$',
  186. ListView.as_view(
  187. models=Poll,
  188. context_object_name='latest_poll_list'
  189. template_name='polls/index.html')),
  190. (r'^(?P<pk>\d+)/$',
  191. DetailView.as_view(
  192. models=Poll,
  193. template_name='polls/detail.html')),
  194. url(r'^(?P<pk>\d+)/results/$',
  195. DetailView.as_view(
  196. models=Poll,
  197. template_name='polls/results.html'),
  198. 'poll_results'),
  199. (r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
  200. )
  201. We're using two generic views here:
  202. :class:`~django.views.generic.list.ListView` and
  203. :class:`~django.views.generic.detail.DetailView`. Respectively, those
  204. two views abstract the concepts of "display a list of objects" and
  205. "display a detail page for a particular type of object."
  206. * Each generic view needs to know what model it will be acting
  207. upon. This is provided using the ``model`` parameter.
  208. * The :class:`~django.views.generic.list.DetailView` generic view
  209. expects the primary key value captured from the URL to be called
  210. ``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic
  211. views.
  212. * We've added a name, ``poll_results``, to the results view so
  213. that we have a way to refer to its URL later on (see the
  214. documentation about :ref:`naming URL patterns
  215. <naming-url-patterns>` for information). We're also using the
  216. :func:`~django.conf.urls.default.url` function from
  217. :mod:`django.conf.urls.defaults` here. It's a good habit to use
  218. :func:`~django.conf.urls.defaults.url` when you are providing a
  219. pattern name like this.
  220. By default, the :class:`~django.views.generic.list.DetailView` generic
  221. view uses a template called ``<app name>/<model name>_detail.html``.
  222. In our case, it'll use the template ``"polls/poll_detail.html"``. The
  223. ``template_name`` argument is used to tell Django to use a specific
  224. template name instead of the autogenerated default template name. We
  225. also specify the ``template_name`` for the ``results`` list view --
  226. this ensures that the results view and the detail view have a
  227. different appearance when rendered, even though they're both a
  228. :class:`~django.views.generic.list.DetailView` behind the scenes.
  229. Similarly, the :class:`~django.views.generic.list.ListView` generic
  230. view uses a default template called ``<app name>/<model
  231. name>_list.html``; we use ``template_name`` to tell
  232. :class:`~django.views.generic.list.ListView` to use our existing
  233. ``"polls/index.html"`` template.
  234. In previous parts of the tutorial, the templates have been provided
  235. with a context that contains the ``poll`` and ``latest_poll_list``
  236. context variables. For DetailView the ``poll`` variable is provided
  237. automatically -- since we're using a Django model (``Poll``), Django
  238. is able to determine an appropriate name for the context variable.
  239. However, for ListView, the automatically generated context variable is
  240. ``poll_list``. To override this we provide the ``context_object_name``
  241. option, specifying that we want to use ``latest_poll_list`` instead.
  242. As an alternative approach, you could change your templates to match
  243. the new default context variables -- but it's a lot easier to just
  244. tell Django to use the variable you want.
  245. You can now delete the ``index()``, ``detail()`` and ``results()``
  246. views from ``polls/views.py``. We don't need them anymore -- they have
  247. been replaced by generic views.
  248. The ``vote()`` view is still required. However, it must be modified to
  249. match the new context variables. In the
  250. :func:`~django.shortcuts.render_to_response` call, rename the ``poll``
  251. context variable to ``object``.
  252. The last thing to do is fix the URL handling to account for the use of
  253. generic views. In the vote view above, we used the
  254. :func:`~django.core.urlresolvers.reverse` function to avoid
  255. hard-coding our URLs. Now that we've switched to a generic view, we'll
  256. need to change the :func:`~django.core.urlresolvers.reverse` call to
  257. point back to our new generic view. We can't simply use the view
  258. function anymore -- generic views can be (and are) used multiple times
  259. -- but we can use the name we've given::
  260. return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
  261. Run the server, and use your new polling app based on generic views.
  262. For full details on generic views, see the :doc:`generic views documentation
  263. </topics/http/generic-views>`.
  264. Coming soon
  265. ===========
  266. The tutorial ends here for the time being. Future installments of the tutorial
  267. will cover:
  268. * Advanced form processing
  269. * Using the RSS framework
  270. * Using the cache framework
  271. * Using the comments framework
  272. * Advanced admin features: Permissions
  273. * Advanced admin features: Custom JavaScript
  274. In the meantime, you might want to check out some pointers on :doc:`where to go
  275. from here </intro/whatsnext>`