Fixed #5550: Documented the context used by the default view for 404 and 500 errors.
[django.git] / docs / tutorial04.txt
blobbd16fa2924e9ae559101f9fb9bb306f21c71cd3a
1 =====================================
2 Writing your first Django app, part 4
3 =====================================
5 This tutorial begins where `Tutorial 3`_ left off. We're continuing the Web-poll
6 application and will focus on simple form processing and cutting down our code.
8 Write a simple form
9 ===================
11 Let's update our poll detail template ("polls/detail.html") from the last
12 tutorial, so that the template contains an HTML ``<form>`` element::
14     <h1>{{ poll.question }}</h1>
16     {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
18     <form action="/polls/{{ poll.id }}/vote/" method="post">
19     {% for choice in poll.choice_set.all %}
20         <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
21         <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
22     {% endfor %}
23     <input type="submit" value="Vote" />
24     </form>
26 A quick rundown:
28     * The above template displays a radio button for each poll choice. The
29       ``value`` of each radio button is the associated poll choice's ID. The
30       ``name`` of each radio button is ``"choice"``. That means, when somebody
31       selects one of the radio buttons and submits the form, it'll send the
32       POST data ``choice=3``. This is HTML Forms 101.
34     * We set the form's ``action`` to ``/polls/{{ poll.id }}/vote/``, and we
35       set ``method="post"``. Using ``method="post"`` (as opposed to
36       ``method="get"``) is very important, because the act of submitting this
37       form will alter data server-side. Whenever you create a form that alters
38       data server-side, use ``method="post"``. This tip isn't specific to
39       Django; it's just good Web development practice.
41 Now, let's create a Django view that handles the submitted data and does
42 something with it. Remember, in `Tutorial 3`_, we created a URLconf for the
43 polls application that includes this line::
45     (r'^(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
47 So let's create a ``vote()`` function in ``mysite/polls/views.py``::
49     from django.shortcuts import get_object_or_404, render_to_response
50     from django.http import HttpResponseRedirect
51     from django.core.urlresolvers import reverse
52     from mysite.polls.models import Choice, Poll
53     # ...
54     def vote(request, poll_id):
55         p = get_object_or_404(Poll, pk=poll_id)
56         try:
57             selected_choice = p.choice_set.get(pk=request.POST['choice'])
58         except (KeyError, Choice.DoesNotExist):
59             # Redisplay the poll voting form.
60             return render_to_response('polls/detail.html', {
61                 'poll': p,
62                 'error_message': "You didn't select a choice.",
63             })
64         else:
65             selected_choice.votes += 1
66             selected_choice.save()
67             # Always return an HttpResponseRedirect after successfully dealing
68             # with POST data. This prevents data from being posted twice if a
69             # user hits the Back button.
70             return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
72 This code includes a few things we haven't covered yet in this tutorial:
74     * ``request.POST`` is a dictionary-like object that lets you access
75       submitted data by key name. In this case, ``request.POST['choice']``
76       returns the ID of the selected choice, as a string. ``request.POST``
77       values are always strings.
79       Note that Django also provides ``request.GET`` for accessing GET data
80       in the same way -- but we're explicitly using ``request.POST`` in our
81       code, to ensure that data is only altered via a POST call.
83     * ``request.POST['choice']`` will raise ``KeyError`` if ``choice`` wasn't
84       provided in POST data. The above code checks for ``KeyError`` and
85       redisplays the poll form with an error message if ``choice`` isn't given.
87     * After incrementing the choice count, the code returns an
88       ``HttpResponseRedirect`` rather than a normal ``HttpResponse``.
89       ``HttpResponseRedirect`` takes a single argument: the URL to which the
90       user will be redirected (see the following point for how we construct
91       the URL in this case).
93       As the Python comment above points out, you should always return an
94       ``HttpResponseRedirect`` after successfully dealing with POST data. This
95       tip isn't specific to Django; it's just good Web development practice.
97     * We are using the ``reverse()`` function in the ``HttpResponseRedirect``
98       constructor in this example. This function helps avoid having to
99       hardcode a URL in the view function. It is given the name of the view
100       that we want to pass control to and the variable portion of the URL
101       pattern that points to that view. In this case, using the URLConf we set
102       up in Tutorial 3, this ``reverse()`` call will return a string like ::
104         '/polls/3/results/'
106       ... where the ``3`` is the value of ``p.id``. This redirected URL will
107       then call the ``'results'`` view to display the final page. Note that
108       you need to use the full name of the view here (including the prefix).
110       For more information about ``reverse()``, see the `URL dispatcher`_
111       documentation.
113 As mentioned in Tutorial 3, ``request`` is a ``HTTPRequest`` object. For more
114 on ``HTTPRequest`` objects, see the `request and response documentation`_.
116 After somebody votes in a poll, the ``vote()`` view redirects to the results
117 page for the poll. Let's write that view::
119     def results(request, poll_id):
120         p = get_object_or_404(Poll, pk=poll_id)
121         return render_to_response('polls/results.html', {'poll': p})
123 This is almost exactly the same as the ``detail()`` view from `Tutorial 3`_.
124 The only difference is the template name. We'll fix this redundancy later.
126 Now, create a ``results.html`` template::
128     <h1>{{ poll.question }}</h1>
130     <ul>
131     {% for choice in poll.choice_set.all %}
132         <li>{{ choice.choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
133     {% endfor %}
134     </ul>
136 Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a
137 results page that gets updated each time you vote. If you submit the form
138 without having chosen a choice, you should see the error message.
140 .. _request and response documentation: ../request_response/
141 .. _URL dispatcher: ../url_dispatch#reverse
143 Use generic views: Less code is better
144 ======================================
146 The ``detail()`` (from `Tutorial 3`_) and ``results()`` views are stupidly
147 simple -- and, as mentioned above, redundant. The ``index()`` view (also from
148 Tutorial 3), which displays a list of polls, is similar.
150 These views represent a common case of basic Web development: getting data from
151 the database according to a parameter passed in the URL, loading a template and
152 returning the rendered template. Because this is so common, Django provides a
153 shortcut, called the "generic views" system.
155 Generic views abstract common patterns to the point where you don't even need
156 to write Python code to write an app.
158 Let's convert our poll app to use the generic views system, so we can delete a
159 bunch of our own code. We'll just have to take a few steps to make the
160 conversion.
162 .. admonition:: Why the code-shuffle?
164     Generally, when writing a Django app, you'll evaluate whether generic views
165     are a good fit for your problem, and you'll use them from the beginning,
166     rather than refactoring your code halfway through. But this tutorial
167     intentionally has focused on writing the views "the hard way" until now, to
168     focus on core concepts.
170     You should know basic math before you start using a calculator.
172 First, open the polls/urls.py URLconf. It looks like this, according to the
173 tutorial so far::
175     from django.conf.urls.defaults import *
177     urlpatterns = patterns('mysite.polls.views',
178         (r'^$', 'index'),
179         (r'^(?P<poll_id>\d+)/$', 'detail'),
180         (r'^(?P<poll_id>\d+)/results/$', 'results'),
181         (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
182     )
184 Change it like so::
186     from django.conf.urls.defaults import *
187     from mysite.polls.models import Poll
189     info_dict = {
190         'queryset': Poll.objects.all(),
191     }
193     urlpatterns = patterns('',
194         (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
195         (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
196         url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
197         (r'^(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
198     )
200 We're using two generic views here: ``object_list`` and ``object_detail``.
201 Respectively, those two views abstract the concepts of "display a list of
202 objects" and "display a detail page for a particular type of object."
204     * Each generic view needs to know what data it will be acting upon. This
205       data is provided in a dictionary. The ``queryset`` key in this dictionary
206       points to the list of objects to be manipulated by the generic view.
208     * The ``object_detail`` generic view expects the ID value captured
209       from the URL to be called ``"object_id"``, so we've changed ``poll_id`` to
210       ``object_id`` for the generic views.
212     * We've added a name, ``poll_results``, to the results view so that we
213       have a way to refer to its URL later on (see the documentation about
214       `naming URL patterns`_ for information). We're also using the `url()`_
215       function from ``django.conf.urls.defaults`` here. It's a good habit to
216       use ``url()`` when you are providing a pattern name like this.
218 .. _naming URL patterns: ../url_dispatch/#naming-url-patterns
219 .. _url(): ../url_dispatch/#url
221 By default, the ``object_detail`` generic view uses a template called
222 ``<app name>/<model name>_detail.html``. In our case, it'll use the template
223 ``"polls/poll_detail.html"``. Thus, rename your ``polls/detail.html`` template to
224 ``polls/poll_detail.html``, and change the ``render_to_response()`` line in
225 ``vote()``.
227 Similarly, the ``object_list`` generic view uses a template called
228 ``<app name>/<model name>_list.html``. Thus, rename ``polls/index.html`` to
229 ``polls/poll_list.html``.
231 Because we have more than one entry in the URLconf that uses ``object_detail``
232 for the polls app, we manually specify a template name for the results view:
233 ``template_name='polls/results.html'``. Otherwise, both views would use the same
234 template. Note that we use ``dict()`` to return an altered dictionary in place.
236 .. note:: ``all()`` is lazy
238     It might look a little frightening to see ``Poll.objects.all()`` being used
239     in a detail view which only needs one ``Poll`` object, but don't worry;
240     ``Poll.objects.all()`` is actually a special object called a ``QuerySet``,
241     which is "lazy" and doesn't hit your database until it absolutely has to. By
242     the time the database query happens, the ``object_detail`` generic view will
243     have narrowed its scope down to a single object, so the eventual query will
244     only select one row from the database. 
245     
246     If you'd like to know more about how that works, The Django database API
247     documentation `explains the lazy nature of QuerySet objects`_.
249 .. _explains the lazy nature of QuerySet objects: ../db-api/#querysets-are-lazy
251 In previous parts of the tutorial, the templates have been provided with a context
252 that contains the ``poll`` and ``latest_poll_list`` context variables. However,
253 the generic views provide the variables ``object`` and ``object_list`` as context.
254 Therefore, you need to change your templates to match the new context variables.
255 Go through your templates, and modify any reference to ``latest_poll_list`` to
256 ``object_list``, and change any reference to ``poll`` to ``object``.
258 You can now delete the ``index()``, ``detail()`` and ``results()`` views
259 from ``polls/views.py``. We don't need them anymore -- they have been replaced
260 by generic views.
262 The ``vote()`` view is still required. However, it must be modified to match
263 the new templates and context variables. Change the template call from
264 ``polls/detail.html`` to ``polls/poll_detail.html``, and pass ``object`` in the
265 context instead of ``poll``.
267 The last thing to do is fix the URL handling to account for the use of generic
268 views. In the vote view above, we used the ``reverse()`` function to avoid
269 hard-coding our URLs. Now that we've switched to a generic view, we'll need to
270 change the ``reverse()`` call to point back to our new generic view. We can't
271 simply use the view function anymore -- generic views can be (and are) used
272 multiple times -- but we can use the name we've given::
273     
274     return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
276 Run the server, and use your new polling app based on generic views.
278 For full details on generic views, see the `generic views documentation`_.
280 .. _generic views documentation: ../generic_views/
282 Coming soon
283 ===========
285 The tutorial ends here for the time being. But check back soon for the next
286 installments:
288     * Advanced form processing
289     * Using the RSS framework
290     * Using the cache framework
291     * Using the comments framework
292     * Advanced admin features: Permissions
293     * Advanced admin features: Custom JavaScript
295 In the meantime, you can read through the rest of the `Django documentation`_
296 and start writing your own applications.
298 .. _Tutorial 3: ../tutorial03/
299 .. _Django documentation: http://www.djangoproject.com/documentation/