tutorial04.txt 14 KB

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