2005-08-09 05:02:28 +08:00
|
|
|
=====================================
|
|
|
|
Writing your first Django app, part 4
|
|
|
|
=====================================
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're
|
2008-08-24 06:25:40 +08:00
|
|
|
continuing the Web-poll application and will focus on simple form processing and
|
|
|
|
cutting down our code.
|
2005-08-09 05:02:28 +08:00
|
|
|
|
|
|
|
Write a simple form
|
|
|
|
===================
|
|
|
|
|
2007-08-05 12:39:52 +08:00
|
|
|
Let's update our poll detail template ("polls/detail.html") from the last
|
2008-08-24 06:25:40 +08:00
|
|
|
tutorial, so that the template contains an HTML ``<form>`` element:
|
|
|
|
|
2013-09-24 06:23:47 +08:00
|
|
|
.. snippet:: html+django
|
|
|
|
:filename: polls/templates/polls/detail.html
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
<h1>{{ question.question_text }}</h1>
|
2005-08-09 05:02:28 +08:00
|
|
|
|
|
|
|
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
|
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
<form action="{% url 'polls:vote' question.id %}" 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-27 07:23:07 +08:00
|
|
|
{% csrf_token %}
|
2013-09-07 02:57:00 +08:00
|
|
|
{% for choice in question.choice_set.all %}
|
2005-08-09 05:02:28 +08:00
|
|
|
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
|
2012-05-26 03:13:51 +08:00
|
|
|
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
|
2005-08-09 05:02:28 +08:00
|
|
|
{% endfor %}
|
|
|
|
<input type="submit" value="Vote" />
|
|
|
|
</form>
|
|
|
|
|
|
|
|
A quick rundown:
|
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
* The above template displays a radio button for each question choice. The
|
|
|
|
``value`` of each radio button is the associated question choice's ID. The
|
2011-10-14 08:12:01 +08:00
|
|
|
``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
|
2013-12-19 07:36:01 +08:00
|
|
|
POST data ``choice=#`` where # is the ID of the selected choice. This is the
|
|
|
|
basic concept of HTML forms.
|
2011-10-14 08:12:01 +08:00
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we
|
2011-10-14 08:12:01 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone
|
|
|
|
through its loop
|
|
|
|
|
|
|
|
* Since we're creating a POST form (which can have the effect of modifying
|
|
|
|
data), we need to worry about Cross Site Request Forgeries.
|
|
|
|
Thankfully, you don't have to worry too hard, because Django comes with
|
|
|
|
a very easy-to-use system for protecting against it. In short, all POST
|
|
|
|
forms that are targeted at internal URLs should use the
|
|
|
|
:ttag:`{% csrf_token %}<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-27 07:23:07 +08:00
|
|
|
|
2005-08-09 05:02:28 +08:00
|
|
|
Now, let's create a Django view that handles the submitted data and does
|
2010-08-20 03:27:44 +08:00
|
|
|
something with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we
|
2013-09-24 06:23:47 +08:00
|
|
|
created a URLconf for the polls application that includes this line:
|
|
|
|
|
|
|
|
.. snippet::
|
|
|
|
:filename: polls/urls.py
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2014-04-15 02:12:44 +08:00
|
|
|
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2009-10-14 21:38:31 +08:00
|
|
|
We also created a dummy implementation of the ``vote()`` function. Let's
|
2013-09-24 06:23:47 +08:00
|
|
|
create a real version. Add the following to ``polls/views.py``:
|
|
|
|
|
|
|
|
.. snippet::
|
|
|
|
:filename: polls/views.py
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2012-10-14 02:37:39 +08:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
2009-10-14 21:38:31 +08:00
|
|
|
from django.http import HttpResponseRedirect, HttpResponse
|
2007-05-27 21:41:10 +08:00
|
|
|
from django.core.urlresolvers import reverse
|
2014-08-02 09:32:53 +08:00
|
|
|
|
2015-02-22 22:59:56 +08:00
|
|
|
from .models import Choice, Question
|
2006-05-02 09:31:56 +08:00
|
|
|
# ...
|
2013-09-07 02:57:00 +08:00
|
|
|
def vote(request, question_id):
|
2015-09-06 19:17:59 +08:00
|
|
|
question = get_object_or_404(Question, pk=question_id)
|
2005-08-09 05:02:28 +08:00
|
|
|
try:
|
2015-09-06 19:17:59 +08:00
|
|
|
selected_choice = question.choice_set.get(pk=request.POST['choice'])
|
2006-05-02 09:31:56 +08:00
|
|
|
except (KeyError, Choice.DoesNotExist):
|
2013-09-07 02:57:00 +08:00
|
|
|
# Redisplay the question voting form.
|
2012-10-14 02:37:39 +08:00
|
|
|
return render(request, 'polls/detail.html', {
|
2015-09-06 19:17:59 +08:00
|
|
|
'question': question,
|
2005-08-09 05:02:28 +08:00
|
|
|
'error_message': "You didn't select a choice.",
|
2012-10-14 02:37:39 +08:00
|
|
|
})
|
2005-08-09 05:02:28 +08: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.
|
2015-09-06 19:17:59 +08:00
|
|
|
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
|
2005-08-09 05:02:28 +08:00
|
|
|
|
|
|
|
This code includes a few things we haven't covered yet in this tutorial:
|
|
|
|
|
2011-10-14 08:12:01 +08: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.
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
2014-04-26 22:00:15 +08:00
|
|
|
* ``request.POST['choice']`` will raise :exc:`KeyError` if
|
2012-12-25 22:56:22 +08:00
|
|
|
``choice`` wasn't provided in POST data. The above code checks for
|
2014-04-26 22:00:15 +08:00
|
|
|
:exc:`KeyError` and redisplays the question form with an error
|
2012-12-25 22:56:22 +08:00
|
|
|
message if ``choice`` isn't given.
|
2011-10-14 08:12:01 +08:00
|
|
|
|
|
|
|
* After incrementing the choice count, the code returns an
|
|
|
|
: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).
|
|
|
|
|
|
|
|
As the Python comment above points out, you should always return an
|
|
|
|
: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
|
2015-05-12 07:43:40 +08:00
|
|
|
case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`,
|
|
|
|
this :func:`~django.core.urlresolvers.reverse` call will return a string like
|
2011-10-14 08:12:01 +08:00
|
|
|
::
|
|
|
|
|
|
|
|
'/polls/3/results/'
|
|
|
|
|
2015-09-06 19:17:59 +08:00
|
|
|
where the ``3`` is the value of ``question.id``. This redirected URL will
|
2012-10-14 02:37:39 +08:00
|
|
|
then call the ``'results'`` view to display the final page.
|
2007-05-27 21:41:10 +08:00
|
|
|
|
2015-05-12 07:43:40 +08:00
|
|
|
As mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an
|
|
|
|
:class:`~django.http.HttpRequest` object. For more on
|
|
|
|
:class:`~django.http.HttpRequest` objects, see the :doc:`request and
|
|
|
|
response documentation </ref/request-response>`.
|
2005-09-03 01:48:18 +08:00
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
After somebody votes in a question, the ``vote()`` view redirects to the results
|
2013-09-24 06:23:47 +08:00
|
|
|
page for the question. Let's write that view:
|
|
|
|
|
|
|
|
.. snippet::
|
|
|
|
:filename: polls/views.py
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2013-05-18 19:34:29 +08:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
|
|
|
|
def results(request, question_id):
|
|
|
|
question = get_object_or_404(Question, pk=question_id)
|
|
|
|
return render(request, 'polls/results.html', {'question': question})
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2010-08-20 03:27:44 +08: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-24 06:25:40 +08:00
|
|
|
redundancy later.
|
|
|
|
|
2012-10-14 02:37:39 +08:00
|
|
|
Now, create a ``polls/results.html`` template:
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2013-09-24 06:23:47 +08:00
|
|
|
.. snippet:: html+django
|
|
|
|
:filename: polls/templates/polls/results.html
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
<h1>{{ question.question_text }}</h1>
|
2005-08-09 05:02:28 +08:00
|
|
|
|
|
|
|
<ul>
|
2013-09-07 02:57:00 +08:00
|
|
|
{% for choice in question.choice_set.all %}
|
2012-05-26 03:13:51 +08:00
|
|
|
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
|
2005-08-09 05:02:28 +08:00
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
|
2010-02-23 23:00:33 +08:00
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
|
2005-08-09 05:02:28 +08:00
|
|
|
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.
|
|
|
|
|
2015-06-04 21:09:28 +08:00
|
|
|
.. note::
|
|
|
|
The code for our ``vote()`` view does have a small problem. It first gets
|
|
|
|
the ``selected_choice`` object from the database, then computes the new
|
|
|
|
value of ``votes``, and then saves it back to the database. If two users of
|
2015-11-15 20:05:15 +08:00
|
|
|
your website try to vote at *exactly the same time*, this might go wrong:
|
2015-06-04 21:09:28 +08:00
|
|
|
The same value, let's say 42, will be retrieved for ``votes``. Then, for
|
|
|
|
both users the new value of 43 is computed and saved, but 44 would be the
|
|
|
|
expected value.
|
|
|
|
|
|
|
|
This is called a *race condition*. If you are interested, you can read
|
|
|
|
:ref:`avoiding-race-conditions-using-f` to learn how you can solve this
|
|
|
|
issue.
|
|
|
|
|
2005-08-09 05:02:28 +08:00
|
|
|
Use generic views: Less code is better
|
|
|
|
======================================
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
|
2014-09-09 03:16:59 +08:00
|
|
|
views are very simple -- and, as mentioned above, redundant. The ``index()``
|
2015-05-12 07:43:40 +08:00
|
|
|
view, which displays a list of polls, is similar.
|
2005-08-09 05:02:28 +08: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-04 02:30:54 +08:00
|
|
|
conversion. We will:
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
1. Convert the URLconf.
|
2009-06-10 20:46:43 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
2. Delete some of the old, unneeded views.
|
2009-06-10 20:46:43 +08:00
|
|
|
|
2013-05-12 07:08:57 +08:00
|
|
|
3. Introduce new views based on Django's generic views.
|
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-04 02:30:54 +08:00
|
|
|
|
|
|
|
Read on for details.
|
2005-08-09 05:02:28 +08: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.
|
|
|
|
|
2013-02-07 18:51:25 +08:00
|
|
|
Amend URLconf
|
|
|
|
-------------
|
|
|
|
|
2013-09-24 06:23:47 +08:00
|
|
|
First, open the ``polls/urls.py`` URLconf and change it like so:
|
|
|
|
|
|
|
|
.. snippet::
|
|
|
|
:filename: polls/urls.py
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2014-04-02 08:46:34 +08:00
|
|
|
from django.conf.urls import url
|
2013-05-12 07:08:57 +08:00
|
|
|
|
2015-02-22 22:59:56 +08:00
|
|
|
from . import views
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2015-12-14 21:56:30 +08:00
|
|
|
app_name = 'polls'
|
2014-04-02 08:46:34 +08:00
|
|
|
urlpatterns = [
|
2013-05-12 07:08:57 +08:00
|
|
|
url(r'^$', views.IndexView.as_view(), name='index'),
|
2014-04-15 02:12:44 +08:00
|
|
|
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
|
|
|
|
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
|
|
|
|
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
|
2014-04-02 08:46:34 +08:00
|
|
|
]
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2014-07-22 06:37:45 +08:00
|
|
|
Note that the name of the matched pattern in the regexes of the second and third
|
|
|
|
patterns has changed from ``<question_id>`` to ``<pk>``.
|
|
|
|
|
2013-02-07 18:51:25 +08:00
|
|
|
Amend views
|
|
|
|
-----------
|
|
|
|
|
2013-05-12 07:08:57 +08:00
|
|
|
Next, we're going to remove our old ``index``, ``detail``, and ``results``
|
|
|
|
views and use Django's generic views instead. To do so, open the
|
2013-09-24 06:23:47 +08:00
|
|
|
``polls/views.py`` file and change it like so:
|
|
|
|
|
|
|
|
.. snippet::
|
|
|
|
:filename: polls/views.py
|
2013-05-12 07:08:57 +08:00
|
|
|
|
|
|
|
from django.shortcuts import get_object_or_404, render
|
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
from django.core.urlresolvers import reverse
|
|
|
|
from django.views import generic
|
|
|
|
|
2015-02-22 22:59:56 +08:00
|
|
|
from .models import Choice, Question
|
2013-09-07 02:57:00 +08:00
|
|
|
|
2013-05-12 07:08:57 +08:00
|
|
|
|
|
|
|
class IndexView(generic.ListView):
|
|
|
|
template_name = 'polls/index.html'
|
2013-09-07 02:57:00 +08:00
|
|
|
context_object_name = 'latest_question_list'
|
2013-05-12 07:08:57 +08:00
|
|
|
|
|
|
|
def get_queryset(self):
|
2013-09-07 02:57:00 +08:00
|
|
|
"""Return the last five published questions."""
|
|
|
|
return Question.objects.order_by('-pub_date')[:5]
|
2013-05-12 07:08:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
class DetailView(generic.DetailView):
|
2013-09-07 02:57:00 +08:00
|
|
|
model = Question
|
2013-05-12 07:08:57 +08:00
|
|
|
template_name = 'polls/detail.html'
|
|
|
|
|
|
|
|
|
|
|
|
class ResultsView(generic.DetailView):
|
2013-09-07 02:57:00 +08:00
|
|
|
model = Question
|
2013-05-12 07:08:57 +08:00
|
|
|
template_name = 'polls/results.html'
|
|
|
|
|
2013-09-07 02:57:00 +08:00
|
|
|
|
|
|
|
def vote(request, question_id):
|
2014-04-19 00:10:46 +08:00
|
|
|
... # same as above
|
2013-05-12 07:08:57 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
We're using two generic views here:
|
2010-10-18 21:34:47 +08:00
|
|
|
:class:`~django.views.generic.list.ListView` and
|
|
|
|
:class:`~django.views.generic.detail.DetailView`. Respectively, those
|
|
|
|
two views abstract the concepts of "display a list of objects" and
|
|
|
|
"display a detail page for a particular type of object."
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Each generic view needs to know what model it will be acting
|
2013-05-12 07:08:57 +08:00
|
|
|
upon. This is provided using the ``model`` attribute.
|
2010-10-18 21:34:47 +08:00
|
|
|
|
2013-01-01 21:12:42 +08:00
|
|
|
* The :class:`~django.views.generic.detail.DetailView` generic view
|
2011-10-14 08:12:01 +08:00
|
|
|
expects the primary key value captured from the URL to be called
|
2013-09-07 02:57:00 +08:00
|
|
|
``"pk"``, so we've changed ``question_id`` to ``pk`` for the generic
|
2011-10-14 08:12:01 +08:00
|
|
|
views.
|
2010-10-18 21:34:47 +08:00
|
|
|
|
2013-01-01 21:12:42 +08:00
|
|
|
By default, the :class:`~django.views.generic.detail.DetailView` generic
|
2010-10-18 21:34:47 +08:00
|
|
|
view uses a template called ``<app name>/<model name>_detail.html``.
|
2013-10-01 22:08:36 +08:00
|
|
|
In our case, it would use the template ``"polls/question_detail.html"``. The
|
2013-05-12 07:08:57 +08:00
|
|
|
``template_name`` attribute is used to tell Django to use a specific
|
2010-10-18 21:34:47 +08:00
|
|
|
template name instead of the autogenerated default template name. We
|
|
|
|
also specify the ``template_name`` for the ``results`` list view --
|
|
|
|
this ensures that the results view and the detail view have a
|
|
|
|
different appearance when rendered, even though they're both a
|
2013-01-01 21:12:42 +08:00
|
|
|
:class:`~django.views.generic.detail.DetailView` behind the scenes.
|
2010-10-18 21:34:47 +08:00
|
|
|
|
|
|
|
Similarly, the :class:`~django.views.generic.list.ListView` generic
|
|
|
|
view uses a default template called ``<app name>/<model
|
|
|
|
name>_list.html``; we use ``template_name`` to tell
|
|
|
|
:class:`~django.views.generic.list.ListView` to use our existing
|
|
|
|
``"polls/index.html"`` template.
|
|
|
|
|
|
|
|
In previous parts of the tutorial, the templates have been provided
|
2013-09-07 02:57:00 +08:00
|
|
|
with a context that contains the ``question`` and ``latest_question_list``
|
|
|
|
context variables. For ``DetailView`` the ``question`` variable is provided
|
|
|
|
automatically -- since we're using a Django model (``Question``), Django
|
2010-10-18 21:34:47 +08:00
|
|
|
is able to determine an appropriate name for the context variable.
|
|
|
|
However, for ListView, the automatically generated context variable is
|
2013-09-07 02:57:00 +08:00
|
|
|
``question_list``. To override this we provide the ``context_object_name``
|
|
|
|
attribute, specifying that we want to use ``latest_question_list`` instead.
|
2010-10-18 21:34:47 +08:00
|
|
|
As an alternative approach, you could change your templates to match
|
|
|
|
the new default context variables -- but it's a lot easier to just
|
|
|
|
tell Django to use the variable you want.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Run the server, and use your new polling app based on generic views.
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
For full details on generic views, see the :doc:`generic views documentation
|
2012-06-11 16:34:00 +08:00
|
|
|
</topics/class-based-views/index>`.
|
2005-08-09 05:02:28 +08:00
|
|
|
|
2012-12-15 21:03:17 +08:00
|
|
|
When you're comfortable with forms and generic views, read :doc:`part 5 of this
|
|
|
|
tutorial</intro/tutorial05>` to learn about testing our polls app.
|