tutorial04.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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>{{ question.question_text }}</h1>
  13. {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
  14. <form action="{% url 'polls:vote' question.id %}" method="post">
  15. {% csrf_token %}
  16. {% for choice in question.choice_set.all %}
  17. <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
  18. <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</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 question choice. The
  24. ``value`` of each radio button is the associated question 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 the basic concept of HTML forms.
  28. * We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, 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
  41. :ttag:`{% csrf_token %}<csrf_token>` template tag.
  42. Now, let's create a Django view that handles the submitted data and does
  43. something with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we
  44. created a URLconf for the polls application that includes this line::
  45. url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
  46. We also created a dummy implementation of the ``vote()`` function. Let's
  47. create a real version. Add the following to ``polls/views.py``::
  48. from django.shortcuts import get_object_or_404, render
  49. from django.http import HttpResponseRedirect, HttpResponse
  50. from django.core.urlresolvers import reverse
  51. from polls.models import Choice, Question
  52. # ...
  53. def vote(request, question_id):
  54. p = get_object_or_404(Question, pk=question_id)
  55. try:
  56. selected_choice = p.choice_set.get(pk=request.POST['choice'])
  57. except (KeyError, Choice.DoesNotExist):
  58. # Redisplay the question voting form.
  59. return render(request, 'polls/detail.html', {
  60. 'question': p,
  61. 'error_message': "You didn't select a choice.",
  62. })
  63. else:
  64. selected_choice.votes += 1
  65. selected_choice.save()
  66. # Always return an HttpResponseRedirect after successfully dealing
  67. # with POST data. This prevents data from being posted twice if a
  68. # user hits the Back button.
  69. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
  70. This code includes a few things we haven't covered yet in this tutorial:
  71. * :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
  72. object that lets you access submitted data by key name. In this case,
  73. ``request.POST['choice']`` returns the ID of the selected choice, as a
  74. string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
  75. always strings.
  76. Note that Django also provides :attr:`request.GET
  77. <django.http.HttpRequest.GET>` for accessing GET data in the same way --
  78. but we're explicitly using :attr:`request.POST
  79. <django.http.HttpRequest.POST>` in our code, to ensure that data is only
  80. altered via a POST call.
  81. * ``request.POST['choice']`` will raise :exc:`~exceptions.KeyError` if
  82. ``choice`` wasn't provided in POST data. The above code checks for
  83. :exc:`~exceptions.KeyError` and redisplays the question form with an error
  84. message if ``choice`` isn't given.
  85. * After incrementing the choice count, the code returns an
  86. :class:`~django.http.HttpResponseRedirect` rather than a normal
  87. :class:`~django.http.HttpResponse`.
  88. :class:`~django.http.HttpResponseRedirect` takes a single argument: the
  89. URL to which the user will be redirected (see the following point for how
  90. we construct the URL in this case).
  91. As the Python comment above points out, you should always return an
  92. :class:`~django.http.HttpResponseRedirect` after successfully dealing with
  93. POST data. This tip isn't specific to Django; it's just good Web
  94. development practice.
  95. * We are using the :func:`~django.core.urlresolvers.reverse` function in the
  96. :class:`~django.http.HttpResponseRedirect` constructor in this example.
  97. This function helps avoid having to hardcode a URL in the view function.
  98. It is given the name of the view that we want to pass control to and the
  99. variable portion of the URL pattern that points to that view. In this
  100. case, using the URLconf we set up in Tutorial 3, this
  101. :func:`~django.core.urlresolvers.reverse` call will return a string like
  102. ::
  103. '/polls/3/results/'
  104. ... where the ``3`` is the value of ``p.id``. This redirected URL will
  105. then call the ``'results'`` view to display the final page.
  106. As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
  107. object. For more on :class:`~django.http.HttpRequest` objects, see the
  108. :doc:`request and response documentation </ref/request-response>`.
  109. After somebody votes in a question, the ``vote()`` view redirects to the results
  110. page for the question. Let's write that view::
  111. from django.shortcuts import get_object_or_404, render
  112. def results(request, question_id):
  113. question = get_object_or_404(Question, pk=question_id)
  114. return render(request, 'polls/results.html', {'question': question})
  115. This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3
  116. </intro/tutorial03>`. The only difference is the template name. We'll fix this
  117. redundancy later.
  118. Now, create a ``polls/results.html`` template:
  119. .. code-block:: html+django
  120. <h1>{{ question.question_text }}</h1>
  121. <ul>
  122. {% for choice in question.choice_set.all %}
  123. <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
  124. {% endfor %}
  125. </ul>
  126. <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
  127. Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
  128. results page that gets updated each time you vote. If you submit the form
  129. without having chosen a choice, you should see the error message.
  130. Use generic views: Less code is better
  131. ======================================
  132. The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
  133. views are stupidly simple -- and, as mentioned above, redundant. The ``index()``
  134. view (also from Tutorial 3), which displays a list of polls, is similar.
  135. These views represent a common case of basic Web development: getting data from
  136. the database according to a parameter passed in the URL, loading a template and
  137. returning the rendered template. Because this is so common, Django provides a
  138. shortcut, called the "generic views" system.
  139. Generic views abstract common patterns to the point where you don't even need
  140. to write Python code to write an app.
  141. Let's convert our poll app to use the generic views system, so we can delete a
  142. bunch of our own code. We'll just have to take a few steps to make the
  143. conversion. We will:
  144. 1. Convert the URLconf.
  145. 2. Delete some of the old, unneeded views.
  146. 3. Introduce new views based on Django's generic views.
  147. Read on for details.
  148. .. admonition:: Why the code-shuffle?
  149. Generally, when writing a Django app, you'll evaluate whether generic views
  150. are a good fit for your problem, and you'll use them from the beginning,
  151. rather than refactoring your code halfway through. But this tutorial
  152. intentionally has focused on writing the views "the hard way" until now, to
  153. focus on core concepts.
  154. You should know basic math before you start using a calculator.
  155. Amend URLconf
  156. -------------
  157. First, open the ``polls/urls.py`` URLconf and change it like so::
  158. from django.conf.urls import patterns, url
  159. from polls import views
  160. urlpatterns = patterns('',
  161. url(r'^$', views.IndexView.as_view(), name='index'),
  162. url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
  163. url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
  164. url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
  165. )
  166. Amend views
  167. -----------
  168. Next, we're going to remove our old ``index``, ``detail``, and ``results``
  169. views and use Django's generic views instead. To do so, open the
  170. ``polls/views.py`` file and change it like so::
  171. from django.shortcuts import get_object_or_404, render
  172. from django.http import HttpResponseRedirect
  173. from django.core.urlresolvers import reverse
  174. from django.views import generic
  175. from polls.models import Choice, Question
  176. class IndexView(generic.ListView):
  177. template_name = 'polls/index.html'
  178. context_object_name = 'latest_question_list'
  179. def get_queryset(self):
  180. """Return the last five published questions."""
  181. return Question.objects.order_by('-pub_date')[:5]
  182. class DetailView(generic.DetailView):
  183. model = Question
  184. template_name = 'polls/detail.html'
  185. class ResultsView(generic.DetailView):
  186. model = Question
  187. template_name = 'polls/results.html'
  188. def vote(request, question_id):
  189. ....
  190. We're using two generic views here:
  191. :class:`~django.views.generic.list.ListView` and
  192. :class:`~django.views.generic.detail.DetailView`. Respectively, those
  193. two views abstract the concepts of "display a list of objects" and
  194. "display a detail page for a particular type of object."
  195. * Each generic view needs to know what model it will be acting
  196. upon. This is provided using the ``model`` attribute.
  197. * The :class:`~django.views.generic.detail.DetailView` generic view
  198. expects the primary key value captured from the URL to be called
  199. ``"pk"``, so we've changed ``question_id`` to ``pk`` for the generic
  200. views.
  201. By default, the :class:`~django.views.generic.detail.DetailView` generic
  202. view uses a template called ``<app name>/<model name>_detail.html``.
  203. In our case, it'll use the template ``"polls/question_detail.html"``. The
  204. ``template_name`` attribute is used to tell Django to use a specific
  205. template name instead of the autogenerated default template name. We
  206. also specify the ``template_name`` for the ``results`` list view --
  207. this ensures that the results view and the detail view have a
  208. different appearance when rendered, even though they're both a
  209. :class:`~django.views.generic.detail.DetailView` behind the scenes.
  210. Similarly, the :class:`~django.views.generic.list.ListView` generic
  211. view uses a default template called ``<app name>/<model
  212. name>_list.html``; we use ``template_name`` to tell
  213. :class:`~django.views.generic.list.ListView` to use our existing
  214. ``"polls/index.html"`` template.
  215. In previous parts of the tutorial, the templates have been provided
  216. with a context that contains the ``question`` and ``latest_question_list``
  217. context variables. For ``DetailView`` the ``question`` variable is provided
  218. automatically -- since we're using a Django model (``Question``), Django
  219. is able to determine an appropriate name for the context variable.
  220. However, for ListView, the automatically generated context variable is
  221. ``question_list``. To override this we provide the ``context_object_name``
  222. attribute, specifying that we want to use ``latest_question_list`` instead.
  223. As an alternative approach, you could change your templates to match
  224. the new default context variables -- but it's a lot easier to just
  225. tell Django to use the variable you want.
  226. Run the server, and use your new polling app based on generic views.
  227. For full details on generic views, see the :doc:`generic views documentation
  228. </topics/class-based-views/index>`.
  229. When you're comfortable with forms and generic views, read :doc:`part 5 of this
  230. tutorial</intro/tutorial05>` to learn about testing our polls app.