2005-08-08 21:02:28 +00:00
|
|
|
=====================================
|
|
|
|
Writing your first Django app, part 4
|
|
|
|
=====================================
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're
|
2008-08-23 22:25:40 +00:00
|
|
|
continuing the Web-poll application and will focus on simple form processing and
|
|
|
|
cutting down our code.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
Write a simple form
|
|
|
|
===================
|
|
|
|
|
2007-08-05 04:39:52 +00:00
|
|
|
Let's update our poll detail template ("polls/detail.html") from the last
|
2008-08-23 22:25:40 +00:00
|
|
|
tutorial, so that the template contains an HTML ``<form>`` element:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
<h1>{{ poll.question }}</h1>
|
|
|
|
|
|
|
|
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
|
|
|
|
|
2009-06-10 12:46:43 +00:00
|
|
|
<form action="/polls/{{ poll.id }}/vote/" method="post">
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
{% csrf_token %}
|
2006-05-02 01:31:56 +00:00
|
|
|
{% for choice in poll.choice_set.all %}
|
2005-08-08 21:02:28 +00:00
|
|
|
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
|
|
|
|
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
|
|
|
|
{% endfor %}
|
|
|
|
<input type="submit" value="Vote" />
|
|
|
|
</form>
|
|
|
|
|
|
|
|
A quick rundown:
|
|
|
|
|
|
|
|
* The above template displays a radio button for each poll choice. The
|
|
|
|
``value`` of each radio button is the associated poll choice's ID. The
|
|
|
|
``name`` of each radio button is ``"choice"``. That means, when somebody
|
|
|
|
selects one of the radio buttons and submits the form, it'll send the
|
|
|
|
POST data ``choice=3``. This is HTML Forms 101.
|
|
|
|
|
2009-06-10 12:46:43 +00:00
|
|
|
* We set the form's ``action`` to ``/polls/{{ poll.id }}/vote/``, and we
|
|
|
|
set ``method="post"``. Using ``method="post"`` (as opposed to
|
|
|
|
``method="get"``) is very important, because the act of submitting this
|
|
|
|
form will alter data server-side. Whenever you create a form that alters
|
|
|
|
data server-side, use ``method="post"``. This tip isn't specific to
|
|
|
|
Django; it's just good Web development practice.
|
2008-03-29 15:48:13 +00:00
|
|
|
|
2008-09-14 08:15:22 +00:00
|
|
|
* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone
|
2008-08-23 22:25:40 +00:00
|
|
|
through its loop
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2010-01-10 17:55:46 +00:00
|
|
|
* Since we're creating a POST form (which can have the effect of modifying
|
|
|
|
data), we need to worry about Cross Site Request Forgeries.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
Thankfully, you don't have to worry too hard, because Django comes with
|
2010-01-10 17:55:46 +00:00
|
|
|
a very easy-to-use system for protecting against it. In short, all POST
|
|
|
|
forms that are targeted at internal URLs should use the ``{% csrf_token %}``
|
|
|
|
template tag.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
|
|
|
|
The ``{% csrf_token %}`` tag requires information from the request object, which
|
2010-01-10 17:55:46 +00:00
|
|
|
is not normally accessible from within the template context. To fix this, a
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
small adjustment needs to be made to the ``detail`` view, so that it looks like
|
|
|
|
the following::
|
|
|
|
|
|
|
|
from django.template import RequestContext
|
|
|
|
# ...
|
|
|
|
def detail(request, poll_id):
|
|
|
|
p = get_object_or_404(Poll, pk=poll_id)
|
|
|
|
return render_to_response('polls/detail.html', {'poll': p},
|
|
|
|
context_instance=RequestContext(request))
|
|
|
|
|
|
|
|
The details of how this works are explained in the documentation for
|
|
|
|
:ref:`RequestContext <subclassing-context-requestcontext>`.
|
|
|
|
|
2005-08-08 21:02:28 +00:00
|
|
|
Now, let's create a Django view that handles the submitted data and does
|
2010-08-19 19:27:44 +00:00
|
|
|
something with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we
|
2009-03-30 19:00:33 +00:00
|
|
|
created a URLconf for the polls application that includes this line::
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2009-03-30 19:00:33 +00:00
|
|
|
(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2009-10-14 13:38:31 +00:00
|
|
|
We also created a dummy implementation of the ``vote()`` function. Let's
|
|
|
|
create a real version. Add the following to ``mysite/polls/views.py``::
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django.shortcuts import get_object_or_404, render_to_response
|
2009-10-14 13:38:31 +00:00
|
|
|
from django.http import HttpResponseRedirect, HttpResponse
|
2007-05-27 13:41:10 +00:00
|
|
|
from django.core.urlresolvers import reverse
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
from django.template import RequestContext
|
2006-05-02 01:31:56 +00:00
|
|
|
from mysite.polls.models import Choice, Poll
|
|
|
|
# ...
|
2005-08-08 21:02:28 +00:00
|
|
|
def vote(request, poll_id):
|
2006-05-02 01:31:56 +00:00
|
|
|
p = get_object_or_404(Poll, pk=poll_id)
|
2005-08-08 21:02:28 +00:00
|
|
|
try:
|
2006-05-02 01:31:56 +00:00
|
|
|
selected_choice = p.choice_set.get(pk=request.POST['choice'])
|
|
|
|
except (KeyError, Choice.DoesNotExist):
|
2005-08-08 21:02:28 +00:00
|
|
|
# Redisplay the poll voting form.
|
2006-05-02 01:31:56 +00:00
|
|
|
return render_to_response('polls/detail.html', {
|
2005-08-08 21:02:28 +00:00
|
|
|
'poll': p,
|
|
|
|
'error_message': "You didn't select a choice.",
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
}, context_instance=RequestContext(request))
|
2005-08-08 21:02:28 +00:00
|
|
|
else:
|
|
|
|
selected_choice.votes += 1
|
|
|
|
selected_choice.save()
|
|
|
|
# Always return an HttpResponseRedirect after successfully dealing
|
|
|
|
# with POST data. This prevents data from being posted twice if a
|
|
|
|
# user hits the Back button.
|
2007-06-01 09:35:29 +00:00
|
|
|
return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
This code includes a few things we haven't covered yet in this tutorial:
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
* :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like
|
|
|
|
object that lets you access submitted data by key name. In this case,
|
|
|
|
``request.POST['choice']`` returns the ID of the selected choice, as a
|
|
|
|
string. :attr:`request.POST <django.http.HttpRequest.POST>` values are
|
|
|
|
always strings.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Note that Django also provides :attr:`request.GET
|
|
|
|
<django.http.HttpRequest.GET>` for accessing GET data in the same way --
|
|
|
|
but we're explicitly using :attr:`request.POST
|
|
|
|
<django.http.HttpRequest.POST>` in our code, to ensure that data is only
|
|
|
|
altered via a POST call.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
* ``request.POST['choice']`` will raise :exc:`KeyError` if ``choice`` wasn't
|
|
|
|
provided in POST data. The above code checks for :exc:`KeyError` and
|
2005-08-08 21:02:28 +00:00
|
|
|
redisplays the poll form with an error message if ``choice`` isn't given.
|
|
|
|
|
|
|
|
* After incrementing the choice count, the code returns an
|
2008-08-23 22:25:40 +00:00
|
|
|
:class:`~django.http.HttpResponseRedirect` rather than a normal
|
|
|
|
:class:`~django.http.HttpResponse`.
|
|
|
|
:class:`~django.http.HttpResponseRedirect` takes a single argument: the
|
|
|
|
URL to which the user will be redirected (see the following point for how
|
|
|
|
we construct the URL in this case).
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
As the Python comment above points out, you should always return an
|
2008-08-23 22:25:40 +00:00
|
|
|
:class:`~django.http.HttpResponseRedirect` after successfully dealing with
|
|
|
|
POST data. This tip isn't specific to Django; it's just good Web
|
|
|
|
development practice.
|
|
|
|
|
|
|
|
* We are using the :func:`~django.core.urlresolvers.reverse` function in the
|
|
|
|
:class:`~django.http.HttpResponseRedirect` constructor in this example.
|
|
|
|
This function helps avoid having to hardcode a URL in the view function.
|
|
|
|
It is given the name of the view that we want to pass control to and the
|
|
|
|
variable portion of the URL pattern that points to that view. In this
|
2008-09-16 05:30:48 +00:00
|
|
|
case, using the URLconf we set up in Tutorial 3, this
|
2008-08-23 22:25:40 +00:00
|
|
|
:func:`~django.core.urlresolvers.reverse` call will return a string like
|
|
|
|
::
|
2007-05-27 13:41:10 +00:00
|
|
|
|
|
|
|
'/polls/3/results/'
|
|
|
|
|
|
|
|
... where the ``3`` is the value of ``p.id``. This redirected URL will
|
2008-08-23 22:25:40 +00:00
|
|
|
then call the ``'results'`` view to display the final page. Note that you
|
|
|
|
need to use the full name of the view here (including the prefix).
|
2007-05-27 13:41:10 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
|
|
|
|
object. For more on :class:`~django.http.HttpRequest` objects, see the
|
2010-08-19 19:27:44 +00:00
|
|
|
:doc:`request and response documentation </ref/request-response>`.
|
2005-09-02 17:48:18 +00:00
|
|
|
|
2005-08-08 21:02:28 +00:00
|
|
|
After somebody votes in a poll, the ``vote()`` view redirects to the results
|
|
|
|
page for the poll. Let's write that view::
|
|
|
|
|
|
|
|
def results(request, poll_id):
|
2006-05-02 01:31:56 +00:00
|
|
|
p = get_object_or_404(Poll, pk=poll_id)
|
|
|
|
return render_to_response('polls/results.html', {'poll': p})
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3
|
|
|
|
</intro/tutorial03>`. The only difference is the template name. We'll fix this
|
2008-08-23 22:25:40 +00:00
|
|
|
redundancy later.
|
|
|
|
|
|
|
|
Now, create a ``results.html`` template:
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. code-block:: html+django
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
<h1>{{ poll.question }}</h1>
|
|
|
|
|
|
|
|
<ul>
|
2006-05-02 01:31:56 +00:00
|
|
|
{% for choice in poll.choice_set.all %}
|
2005-08-08 21:02:28 +00:00
|
|
|
<li>{{ choice.choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
|
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
|
2010-02-23 15:00:33 +00:00
|
|
|
<a href="/polls/{{ poll.id }}/">Vote again?</a>
|
|
|
|
|
2005-08-08 21:02:28 +00:00
|
|
|
Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a
|
|
|
|
results page that gets updated each time you vote. If you submit the form
|
|
|
|
without having chosen a choice, you should see the error message.
|
|
|
|
|
|
|
|
Use generic views: Less code is better
|
|
|
|
======================================
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
|
2008-08-23 22:25:40 +00:00
|
|
|
views are stupidly simple -- and, as mentioned above, redundant. The ``index()``
|
|
|
|
view (also from Tutorial 3), which displays a list of polls, is similar.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
These views represent a common case of basic Web development: getting data from
|
|
|
|
the database according to a parameter passed in the URL, loading a template and
|
|
|
|
returning the rendered template. Because this is so common, Django provides a
|
|
|
|
shortcut, called the "generic views" system.
|
|
|
|
|
|
|
|
Generic views abstract common patterns to the point where you don't even need
|
|
|
|
to write Python code to write an app.
|
|
|
|
|
|
|
|
Let's convert our poll app to use the generic views system, so we can delete a
|
|
|
|
bunch of our own code. We'll just have to take a few steps to make the
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
conversion. We will:
|
|
|
|
|
|
|
|
1. Convert the URLconf.
|
2009-06-10 12:46:43 +00:00
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
2. Rename a few templates.
|
2009-06-10 12:46:43 +00:00
|
|
|
|
2010-01-10 17:54:34 +00:00
|
|
|
3. Delete some of the old, unneeded views.
|
2009-06-10 12:46:43 +00:00
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
4. Fix up URL handling for the new views.
|
|
|
|
|
|
|
|
Read on for details.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
.. admonition:: Why the code-shuffle?
|
|
|
|
|
|
|
|
Generally, when writing a Django app, you'll evaluate whether generic views
|
|
|
|
are a good fit for your problem, and you'll use them from the beginning,
|
|
|
|
rather than refactoring your code halfway through. But this tutorial
|
|
|
|
intentionally has focused on writing the views "the hard way" until now, to
|
|
|
|
focus on core concepts.
|
|
|
|
|
|
|
|
You should know basic math before you start using a calculator.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
First, open the ``polls/urls.py`` URLconf. It looks like this, according to the
|
2006-05-02 01:31:56 +00:00
|
|
|
tutorial so far::
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
urlpatterns = patterns('mysite.polls.views',
|
2005-08-08 21:02:28 +00:00
|
|
|
(r'^$', 'index'),
|
|
|
|
(r'^(?P<poll_id>\d+)/$', 'detail'),
|
|
|
|
(r'^(?P<poll_id>\d+)/results/$', 'results'),
|
|
|
|
(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
|
|
|
|
)
|
|
|
|
|
|
|
|
Change it like so::
|
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
2006-05-02 01:31:56 +00:00
|
|
|
from mysite.polls.models import Poll
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
info_dict = {
|
2006-05-02 01:31:56 +00:00
|
|
|
'queryset': Poll.objects.all(),
|
2005-08-08 21:02:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
urlpatterns = patterns('',
|
|
|
|
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
|
|
|
|
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
|
2007-08-19 15:08:48 +00:00
|
|
|
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
|
2006-05-02 01:31:56 +00:00
|
|
|
(r'^(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
|
2005-08-08 21:02:28 +00:00
|
|
|
)
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
We're using two generic views here:
|
|
|
|
:func:`~django.views.generic.list_detail.object_list` and
|
|
|
|
:func:`~django.views.generic.list_detail.object_detail`. Respectively, those two
|
|
|
|
views abstract the concepts of "display a list of objects" and "display a detail
|
|
|
|
page for a particular type of object."
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
* Each generic view needs to know what data it will be acting upon. This
|
|
|
|
data is provided in a dictionary. The ``queryset`` key in this dictionary
|
|
|
|
points to the list of objects to be manipulated by the generic view.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
* The :func:`~django.views.generic.list_detail.object_detail` generic view
|
|
|
|
expects the ID value captured from the URL to be called ``"object_id"``,
|
|
|
|
so we've changed ``poll_id`` to ``object_id`` for the generic views.
|
|
|
|
|
|
|
|
* We've added a name, ``poll_results``, to the results view so that we have
|
|
|
|
a way to refer to its URL later on (see the documentation about
|
|
|
|
:ref:`naming URL patterns <naming-url-patterns>` for information). We're
|
|
|
|
also using the :func:`~django.conf.urls.default.url` function from
|
|
|
|
:mod:`django.conf.urls.defaults` here. It's a good habit to use
|
|
|
|
:func:`~django.conf.urls.defaults.url` when you are providing a pattern
|
|
|
|
name like this.
|
|
|
|
|
|
|
|
By default, the :func:`~django.views.generic.list_detail.object_detail` generic
|
|
|
|
view uses a template called ``<app name>/<model name>_detail.html``. In our
|
|
|
|
case, it'll use the template ``"polls/poll_detail.html"``. Thus, rename your
|
|
|
|
``polls/detail.html`` template to ``polls/poll_detail.html``, and change the
|
|
|
|
:func:`~django.shortcuts.render_to_response` line in ``vote()``.
|
|
|
|
|
|
|
|
Similarly, the :func:`~django.views.generic.list_detail.object_list` generic
|
|
|
|
view uses a template called ``<app name>/<model name>_list.html``. Thus, rename
|
|
|
|
``polls/index.html`` to ``polls/poll_list.html``.
|
|
|
|
|
|
|
|
Because we have more than one entry in the URLconf that uses
|
|
|
|
:func:`~django.views.generic.list_detail.object_detail` for the polls app, we
|
|
|
|
manually specify a template name for the results view:
|
2006-05-02 01:31:56 +00:00
|
|
|
``template_name='polls/results.html'``. Otherwise, both views would use the same
|
2005-08-08 21:02:28 +00:00
|
|
|
template. Note that we use ``dict()`` to return an altered dictionary in place.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. note:: :meth:`django.db.models.QuerySet.all` is lazy
|
2007-02-27 04:27:47 +00:00
|
|
|
|
|
|
|
It might look a little frightening to see ``Poll.objects.all()`` being used
|
|
|
|
in a detail view which only needs one ``Poll`` object, but don't worry;
|
2008-08-23 22:25:40 +00:00
|
|
|
``Poll.objects.all()`` is actually a special object called a
|
|
|
|
:class:`~django.db.models.QuerySet`, which is "lazy" and doesn't hit your
|
|
|
|
database until it absolutely has to. By the time the database query happens,
|
|
|
|
the :func:`~django.views.generic.list_detail.object_detail` generic view
|
|
|
|
will have narrowed its scope down to a single object, so the eventual query
|
|
|
|
will only select one row from the database.
|
2008-03-29 15:48:13 +00:00
|
|
|
|
2007-02-27 04:27:47 +00:00
|
|
|
If you'd like to know more about how that works, The Django database API
|
2008-08-23 22:25:40 +00:00
|
|
|
documentation :ref:`explains the lazy nature of QuerySet objects
|
|
|
|
<querysets-are-lazy>`.
|
2007-02-27 04:27:47 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
In previous parts of the tutorial, the templates have been provided with a
|
|
|
|
context that contains the ``poll`` and ``latest_poll_list`` context variables.
|
|
|
|
However, the generic views provide the variables ``object`` and ``object_list``
|
|
|
|
as context. Therefore, you need to change your templates to match the new
|
|
|
|
context variables. Go through your templates, and modify any reference to
|
2008-09-14 08:28:55 +00:00
|
|
|
``latest_poll_list`` to ``object_list``, and change any reference to ``poll``
|
|
|
|
to ``object``.
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
You can now delete the ``index()``, ``detail()`` and ``results()`` views
|
|
|
|
from ``polls/views.py``. We don't need them anymore -- they have been replaced
|
|
|
|
by generic views.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The ``vote()`` view is still required. However, it must be modified to match the
|
|
|
|
new context variables. In the :func:`~django.shortcuts.render_to_response` call,
|
|
|
|
rename the ``poll`` context variable to ``object``.
|
2005-11-01 00:49:52 +00:00
|
|
|
|
2007-07-12 04:44:45 +00:00
|
|
|
The last thing to do is fix the URL handling to account for the use of generic
|
2008-08-23 22:25:40 +00:00
|
|
|
views. In the vote view above, we used the
|
|
|
|
:func:`~django.core.urlresolvers.reverse` function to avoid hard-coding our
|
|
|
|
URLs. Now that we've switched to a generic view, we'll need to change the
|
|
|
|
:func:`~django.core.urlresolvers.reverse` call to point back to our new generic
|
|
|
|
view. We can't simply use the view function anymore -- generic views can be (and
|
|
|
|
are) used multiple times -- but we can use the name we've given::
|
2008-03-29 15:48:13 +00:00
|
|
|
|
2007-07-12 00:33:44 +00:00
|
|
|
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
Run the server, and use your new polling app based on generic views.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
For full details on generic views, see the :doc:`generic views documentation
|
|
|
|
</topics/http/generic-views>`.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
Coming soon
|
|
|
|
===========
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The tutorial ends here for the time being. Future installments of the tutorial
|
|
|
|
will cover:
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
* Advanced form processing
|
|
|
|
* Using the RSS framework
|
|
|
|
* Using the cache framework
|
|
|
|
* Using the comments framework
|
|
|
|
* Advanced admin features: Permissions
|
|
|
|
* Advanced admin features: Custom JavaScript
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
In the meantime, you might want to check out some pointers on :doc:`where to go
|
|
|
|
from here </intro/whatsnext>`
|