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
|
2021-07-23 06:48:16 +00:00
|
|
|
continuing the web-poll application and will focus on form processing and
|
2008-08-23 22:25:40 +00:00
|
|
|
cutting down our code.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2019-12-21 13:58:46 +00:00
|
|
|
.. admonition:: Where to get help:
|
|
|
|
|
|
|
|
If you're having trouble going through this tutorial, please head over to
|
|
|
|
the :doc:`Getting Help</faq/help>` section of the FAQ.
|
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
Write a minimal form
|
|
|
|
====================
|
2005-08-08 21:02:28 +00:00
|
|
|
|
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:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/templates/polls/detail.html``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2013-09-06 18:57:00 +00: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-26 23:23:07 +00:00
|
|
|
{% csrf_token %}
|
2021-05-14 07:46:22 +00:00
|
|
|
<fieldset>
|
|
|
|
<legend><h1>{{ question.question_text }}</h1></legend>
|
|
|
|
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
|
|
|
|
{% for choice in question.choice_set.all %}
|
|
|
|
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
|
|
|
|
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
|
|
|
|
{% endfor %}
|
|
|
|
</fieldset>
|
2018-01-21 07:09:10 +00:00
|
|
|
<input type="submit" value="Vote">
|
2005-08-08 21:02:28 +00:00
|
|
|
</form>
|
|
|
|
|
|
|
|
A quick rundown:
|
|
|
|
|
2013-09-06 18:57:00 +00: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 00:12:01 +00: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-18 23:36:01 +00:00
|
|
|
POST data ``choice=#`` where # is the ID of the selected choice. This is the
|
|
|
|
basic concept of HTML forms.
|
2011-10-14 00:12:01 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we
|
2011-10-14 00:12:01 +00: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
|
2021-07-23 06:48:16 +00:00
|
|
|
Django; it's good web development practice in general.
|
2011-10-14 00:12:01 +00:00
|
|
|
|
|
|
|
* ``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.
|
2019-06-17 14:54:55 +00:00
|
|
|
Thankfully, you don't have to worry too hard, because Django comes with a
|
|
|
|
helpful 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-26 23:23:07 +00:00
|
|
|
|
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
|
2013-09-23 22:23:47 +00:00
|
|
|
created a URLconf for the polls application that includes this line:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/urls.py``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
path("<int:question_id>/vote/", views.vote, name="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
|
2013-09-23 22:23:47 +00:00
|
|
|
create a real version. Add the following to ``polls/views.py``:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/views.py``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2024-02-20 15:26:21 +00:00
|
|
|
from django.db.models import F
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.http import HttpResponse, HttpResponseRedirect
|
2012-10-13 18:37:39 +00:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
2015-12-30 15:51:16 +00:00
|
|
|
from django.urls import reverse
|
2014-08-02 01:32:53 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Choice, Question
|
2023-02-28 19:53:28 +00:00
|
|
|
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
# ...
|
2013-09-06 18:57:00 +00:00
|
|
|
def vote(request, question_id):
|
2015-09-06 11:17:59 +00:00
|
|
|
question = get_object_or_404(Question, pk=question_id)
|
2005-08-08 21:02:28 +00:00
|
|
|
try:
|
2015-09-06 11:17:59 +00:00
|
|
|
selected_choice = question.choice_set.get(pk=request.POST["choice"])
|
2006-05-02 01:31:56 +00:00
|
|
|
except (KeyError, Choice.DoesNotExist):
|
2013-09-06 18:57:00 +00:00
|
|
|
# Redisplay the question voting form.
|
2012-10-13 18:37:39 +00:00
|
|
|
return render(
|
|
|
|
request,
|
|
|
|
"polls/detail.html",
|
|
|
|
{
|
2015-09-06 11:17:59 +00:00
|
|
|
"question": question,
|
2005-08-08 21:02:28 +00:00
|
|
|
"error_message": "You didn't select a choice.",
|
2012-10-13 18:37:39 +00:00
|
|
|
},
|
|
|
|
)
|
2005-08-08 21:02:28 +00:00
|
|
|
else:
|
2024-02-20 15:26:21 +00:00
|
|
|
selected_choice.votes = F("votes") + 1
|
2005-08-08 21:02:28 +00:00
|
|
|
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 11:17:59 +00:00
|
|
|
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
This code includes a few things we haven't covered yet in this tutorial:
|
|
|
|
|
2011-10-14 00:12:01 +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.
|
|
|
|
|
|
|
|
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 14:00:15 +00:00
|
|
|
* ``request.POST['choice']`` will raise :exc:`KeyError` if
|
2012-12-25 14:56:22 +00:00
|
|
|
``choice`` wasn't provided in POST data. The above code checks for
|
2014-04-26 14:00:15 +00:00
|
|
|
:exc:`KeyError` and redisplays the question form with an error
|
2012-12-25 14:56:22 +00:00
|
|
|
message if ``choice`` isn't given.
|
2011-10-14 00:12:01 +00:00
|
|
|
|
2024-02-20 15:26:21 +00:00
|
|
|
* ``F("votes") + 1`` :ref:`instructs the database
|
|
|
|
<avoiding-race-conditions-using-f>` to increase the vote count by 1.
|
|
|
|
|
2011-10-14 00:12:01 +00: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
|
2021-07-23 06:48:16 +00:00
|
|
|
POST data. This tip isn't specific to Django; it's good web development
|
2019-06-17 14:54:55 +00:00
|
|
|
practice in general.
|
2011-10-14 00:12:01 +00:00
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
* We are using the :func:`~django.urls.reverse` function in the
|
2011-10-14 00:12:01 +00:00
|
|
|
: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-11 23:43:40 +00:00
|
|
|
case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`,
|
2015-12-30 15:51:16 +00:00
|
|
|
this :func:`~django.urls.reverse` call will return a string like
|
2011-10-14 00:12:01 +00:00
|
|
|
::
|
|
|
|
|
|
|
|
"/polls/3/results/"
|
|
|
|
|
2015-09-06 11:17:59 +00:00
|
|
|
where the ``3`` is the value of ``question.id``. This redirected URL will
|
2012-10-13 18:37:39 +00:00
|
|
|
then call the ``'results'`` view to display the final page.
|
2007-05-27 13:41:10 +00:00
|
|
|
|
2015-05-11 23:43:40 +00: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-02 17:48:18 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
After somebody votes in a question, the ``vote()`` view redirects to the results
|
2013-09-23 22:23:47 +00:00
|
|
|
page for the question. Let's write that view:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/views.py``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2013-05-18 11:34:29 +00:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
|
|
|
|
2013-09-06 18:57:00 +00: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-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.
|
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Now, create a ``polls/results.html`` template:
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/templates/polls/results.html``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<h1>{{ question.question_text }}</h1>
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
<ul>
|
2013-09-06 18:57:00 +00:00
|
|
|
{% for choice in question.choice_set.all %}
|
2012-05-25 19:13:51 +00:00
|
|
|
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
|
2005-08-08 21:02:28 +00:00
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
|
2010-02-23 15:00:33 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
|
2005-08-08 21:02:28 +00: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.
|
|
|
|
|
|
|
|
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()``
|
2019-06-17 14:54:55 +00:00
|
|
|
views are very short -- and, as mentioned above, redundant. The ``index()``
|
2015-05-11 23:43:40 +00:00
|
|
|
view, which displays a list of polls, is similar.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2021-07-23 06:48:16 +00:00
|
|
|
These views represent a common case of basic web development: getting data from
|
2005-08-08 21:02:28 +00:00
|
|
|
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.
|
|
|
|
|
2023-05-25 14:18:26 +00:00
|
|
|
Generic views abstract common patterns to the point where you don't even need to
|
|
|
|
write Python code to write an app. For example, the
|
|
|
|
:class:`~django.views.generic.list.ListView` and
|
|
|
|
:class:`~django.views.generic.detail.DetailView` generic views
|
|
|
|
abstract the concepts of "display a list of objects" and
|
|
|
|
"display a detail page for a particular type of object" respectively.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
|
|
|
Let's convert our poll app to use the generic views system, so we can delete a
|
2019-06-17 14:54:55 +00:00
|
|
|
bunch of our own code. We'll have to take a few steps to make the conversion.
|
|
|
|
We will:
|
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
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Convert the URLconf.
|
2009-06-10 12:46:43 +00:00
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Delete some of the old, unneeded views.
|
2009-06-10 12:46:43 +00:00
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. 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-03 18:30:54 +00:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2013-02-07 10:51:25 +00:00
|
|
|
Amend URLconf
|
|
|
|
-------------
|
|
|
|
|
2013-09-23 22:23:47 +00:00
|
|
|
First, open the ``polls/urls.py`` URLconf and change it like so:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/urls.py``
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
from django.urls import path
|
2013-05-11 23:08:57 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from . import views
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2015-12-14 13:56:30 +00:00
|
|
|
app_name = "polls"
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path("", views.IndexView.as_view(), name="index"),
|
|
|
|
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
|
|
|
|
path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
|
|
|
|
path("<int:question_id>/vote/", views.vote, name="vote"),
|
2014-04-02 00:46:34 +00:00
|
|
|
]
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
Note that the name of the matched pattern in the path strings of the second and
|
2023-05-25 14:18:26 +00:00
|
|
|
third patterns has changed from ``<question_id>`` to ``<pk>``. This is
|
|
|
|
necessary because we'll use the
|
|
|
|
:class:`~django.views.generic.detail.DetailView` generic view to replace our
|
|
|
|
``detail()`` and ``results()`` views, and it expects the primary key value
|
|
|
|
captured from the URL to be called ``"pk"``.
|
2014-07-21 22:37:45 +00:00
|
|
|
|
2013-02-07 10:51:25 +00:00
|
|
|
Amend views
|
|
|
|
-----------
|
|
|
|
|
2013-05-11 23:08:57 +00: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-23 22:23:47 +00:00
|
|
|
``polls/views.py`` file and change it like so:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
2022-05-31 05:40:54 +00:00
|
|
|
:caption: ``polls/views.py``
|
2013-05-11 23:08:57 +00:00
|
|
|
|
|
|
|
from django.http import HttpResponseRedirect
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
2015-12-30 15:51:16 +00:00
|
|
|
from django.urls import reverse
|
2013-05-11 23:08:57 +00:00
|
|
|
from django.views import generic
|
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Choice, Question
|
2013-09-06 18:57:00 +00:00
|
|
|
|
2013-05-11 23:08:57 +00:00
|
|
|
|
|
|
|
class IndexView(generic.ListView):
|
|
|
|
template_name = "polls/index.html"
|
2013-09-06 18:57:00 +00:00
|
|
|
context_object_name = "latest_question_list"
|
2013-05-11 23:08:57 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
2013-09-06 18:57:00 +00:00
|
|
|
"""Return the last five published questions."""
|
|
|
|
return Question.objects.order_by("-pub_date")[:5]
|
2013-05-11 23:08:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
class DetailView(generic.DetailView):
|
2013-09-06 18:57:00 +00:00
|
|
|
model = Question
|
2013-05-11 23:08:57 +00:00
|
|
|
template_name = "polls/detail.html"
|
|
|
|
|
|
|
|
|
|
|
|
class ResultsView(generic.DetailView):
|
2013-09-06 18:57:00 +00:00
|
|
|
model = Question
|
2013-05-11 23:08:57 +00:00
|
|
|
template_name = "polls/results.html"
|
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
|
|
|
|
def vote(request, question_id):
|
2016-01-31 23:02:33 +00:00
|
|
|
# same as above, no changes needed.
|
|
|
|
...
|
2013-05-11 23:08:57 +00:00
|
|
|
|
2023-05-25 14:18:26 +00:00
|
|
|
Each generic view needs to know what model it will be acting upon. This is
|
|
|
|
provided using either the ``model`` attribute (in this example, ``model =
|
|
|
|
Question`` for ``DetailView`` and ``ResultsView``) or by defining the
|
|
|
|
:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method (as
|
|
|
|
shown in ``IndexView``).
|
2010-10-18 13:34:47 +00:00
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
By default, the :class:`~django.views.generic.detail.DetailView` generic
|
2010-10-18 13:34:47 +00:00
|
|
|
view uses a template called ``<app name>/<model name>_detail.html``.
|
2013-10-01 14:08:36 +00:00
|
|
|
In our case, it would use the template ``"polls/question_detail.html"``. The
|
2013-05-11 23:08:57 +00:00
|
|
|
``template_name`` attribute is used to tell Django to use a specific
|
2010-10-18 13:34:47 +00: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 13:12:42 +00:00
|
|
|
:class:`~django.views.generic.detail.DetailView` behind the scenes.
|
2010-10-18 13:34:47 +00: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-06 18:57:00 +00: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 13:34:47 +00:00
|
|
|
is able to determine an appropriate name for the context variable.
|
|
|
|
However, for ListView, the automatically generated context variable is
|
2013-09-06 18:57:00 +00: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 13:34:47 +00:00
|
|
|
As an alternative approach, you could change your templates to match
|
2019-06-17 14:54:55 +00:00
|
|
|
the new default context variables -- but it's a lot easier to tell Django to
|
|
|
|
use the variable you want.
|
2010-10-18 13:34:47 +00:00
|
|
|
|
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
|
2012-06-11 08:34:00 +00:00
|
|
|
</topics/class-based-views/index>`.
|
2005-08-08 21:02:28 +00:00
|
|
|
|
2012-12-15 13:03:17 +00: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.
|