tutorial04.txt 13 KB

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