2005-07-19 05:43:07 +00:00
|
|
|
=====================================
|
|
|
|
Writing your first Django app, part 3
|
|
|
|
=====================================
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
|
2008-08-23 22:25:40 +00:00
|
|
|
continuing the Web-poll application and will focus on creating the public
|
|
|
|
interface -- "views."
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2015-05-11 23:43:40 +00:00
|
|
|
Overview
|
|
|
|
========
|
2005-07-21 17:59:05 +00:00
|
|
|
|
2005-08-08 15:47:57 +00:00
|
|
|
A view is a "type" of Web page in your Django application that generally serves
|
2012-10-13 18:37:39 +00:00
|
|
|
a specific function and has a specific template. For example, in a blog
|
2005-08-08 15:47:57 +00:00
|
|
|
application, you might have the following views:
|
2005-07-22 18:45:22 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Blog homepage -- displays the latest few entries.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Entry "detail" page -- permalink page for a single entry.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Year-based archive page -- displays all months with entries in the
|
|
|
|
given year.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Month-based archive page -- displays all days with entries in the
|
|
|
|
given month.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Day-based archive page -- displays all entries in the given day.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Comment action -- handles posting comments to a given entry.
|
2005-07-22 18:45:22 +00:00
|
|
|
|
2005-08-08 15:47:57 +00:00
|
|
|
In our poll application, we'll have the following four views:
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
* Question "index" page -- displays the latest few questions.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
* Question "detail" page -- displays a question text, with no results but
|
2011-10-14 00:12:01 +00:00
|
|
|
with a form to vote.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
* Question "results" page -- displays results for a particular question.
|
2009-06-17 13:46:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Vote action -- handles voting for a particular choice in a particular
|
2013-09-06 18:57:00 +00:00
|
|
|
question.
|
2005-08-01 19:02:55 +00:00
|
|
|
|
2013-02-07 10:51:25 +00:00
|
|
|
In Django, web pages and other content are delivered by views. Each view is
|
|
|
|
represented by a simple Python function (or method, in the case of class-based
|
|
|
|
views). Django will choose a view by examining the URL that's requested (to be
|
|
|
|
precise, the part of the URL after the domain name).
|
|
|
|
|
|
|
|
Now in your time on the web you may have come across such beauties as
|
|
|
|
"ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B".
|
|
|
|
You will be pleased to know that Django allows us much more elegant
|
|
|
|
*URL patterns* than that.
|
|
|
|
|
|
|
|
A URL pattern is simply the general form of a URL - for example:
|
|
|
|
``/newsarchive/<year>/<month>/``.
|
|
|
|
|
|
|
|
To get from a URL to a view, Django uses what are known as 'URLconfs'. A
|
2016-10-20 17:29:04 +00:00
|
|
|
URLconf maps URL patterns to views.
|
2013-02-07 10:51:25 +00:00
|
|
|
|
|
|
|
This tutorial provides basic instruction in the use of URLconfs, and you can
|
2016-10-20 17:29:04 +00:00
|
|
|
refer to :doc:`/topics/http/urls` for more information.
|
2005-08-01 19:02:55 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Writing more views
|
|
|
|
==================
|
2005-11-16 02:00:23 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Now let's add a few more views to ``polls/views.py``. These views are
|
2013-09-23 22:23:47 +00:00
|
|
|
slightly different, because they take an argument:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2005-11-16 02:00:23 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
def detail(request, question_id):
|
|
|
|
return HttpResponse("You're looking at question %s." % question_id)
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
def results(request, question_id):
|
|
|
|
response = "You're looking at the results of question %s."
|
|
|
|
return HttpResponse(response % question_id)
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
def vote(request, question_id):
|
|
|
|
return HttpResponse("You're voting on question %s." % question_id)
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-07-18 11:58:51 +00:00
|
|
|
Wire these new views into the ``polls.urls`` module by adding the following
|
2016-10-20 17:29:04 +00:00
|
|
|
:func:`~django.urls.path` calls:
|
2013-09-23 22:23:47 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/urls.py
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
from django.urls import path
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from . import views
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns = [
|
2012-10-13 18:37:39 +00:00
|
|
|
# ex: /polls/
|
2016-10-20 17:29:04 +00:00
|
|
|
path('', views.index, name='index'),
|
2012-10-13 18:37:39 +00:00
|
|
|
# ex: /polls/5/
|
2016-10-20 17:29:04 +00:00
|
|
|
path('<int:question_id>/', views.detail, name='detail'),
|
2012-10-13 18:37:39 +00:00
|
|
|
# ex: /polls/5/results/
|
2016-10-20 17:29:04 +00:00
|
|
|
path('<int:question_id>/results/', views.results, name='results'),
|
2012-10-13 18:37:39 +00:00
|
|
|
# ex: /polls/5/vote/
|
2016-10-20 17:29:04 +00:00
|
|
|
path('<int:question_id>/vote/', views.vote, name='vote'),
|
2014-04-02 00:46:34 +00:00
|
|
|
]
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Take a look in your browser, at "/polls/34/". It'll run the ``detail()``
|
|
|
|
method and display whatever ID you provide in the URL. Try
|
|
|
|
"/polls/34/results/" and "/polls/34/vote/" too -- these will display the
|
|
|
|
placeholder results and voting pages.
|
|
|
|
|
2015-11-15 12:05:15 +00:00
|
|
|
When somebody requests a page from your website -- say, "/polls/34/", Django
|
2012-10-13 18:37:39 +00:00
|
|
|
will load the ``mysite.urls`` Python module because it's pointed to by the
|
|
|
|
:setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``
|
2016-10-20 17:29:04 +00:00
|
|
|
and traverses the patterns in order. After finding the match at ``'polls/'``,
|
|
|
|
it strips off the matching text (``"polls/"``) and sends the remaining text --
|
|
|
|
``"34/"`` -- to the 'polls.urls' URLconf for further processing. There it
|
|
|
|
matches ``'<int:question_id>/'``, resulting in a call to the ``detail()`` view
|
|
|
|
like so::
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
detail(request=<HttpRequest object>, question_id=34)
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
The ``question_id=34`` part comes from ``<int:question_id>``. Using angle
|
|
|
|
brackets "captures" part of the URL and sends it as a keyword argument to the
|
|
|
|
view function. The ``:question_id>`` part of the string defines the name that
|
|
|
|
will be used to identify the matched pattern, and the ``<int:`` part is a
|
|
|
|
converter that determines what patterns should match this part of the URL path.
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
There's no need to add URL cruft such as ``.html`` -- unless you want to, in
|
|
|
|
which case you can do something like this::
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
path('polls/latest.html', views.index),
|
2012-10-13 18:37:39 +00:00
|
|
|
|
|
|
|
But, don't do that. It's silly.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
|
|
|
Write views that actually do something
|
|
|
|
======================================
|
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Each view is responsible for doing one of two things: returning an
|
2008-08-23 22:25:40 +00:00
|
|
|
:class:`~django.http.HttpResponse` object containing the content for the
|
|
|
|
requested page, or raising an exception such as :exc:`~django.http.Http404`. The
|
|
|
|
rest is up to you.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
|
|
|
Your view can read records from a database, or not. It can use a template
|
|
|
|
system such as Django's -- or a third-party Python template system -- or not.
|
|
|
|
It can generate a PDF file, output XML, create a ZIP file on the fly, anything
|
|
|
|
you want, using whatever Python libraries you want.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
|
|
|
Because it's convenient, let's use Django's own database API, which we covered
|
2015-05-11 23:43:40 +00:00
|
|
|
in :doc:`Tutorial 2 </intro/tutorial02>`. Here's one stab at a new ``index()``
|
2008-08-23 22:25:40 +00:00
|
|
|
view, which displays the latest 5 poll questions in the system, separated by
|
2013-09-23 22:23:47 +00:00
|
|
|
commas, according to publication date:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django.http import HttpResponse
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Question
|
2013-09-06 18:57:00 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2005-07-19 05:43:07 +00:00
|
|
|
def index(request):
|
2013-09-06 18:57:00 +00:00
|
|
|
latest_question_list = Question.objects.order_by('-pub_date')[:5]
|
2015-09-06 11:17:59 +00:00
|
|
|
output = ', '.join([q.question_text for q in latest_question_list])
|
2005-07-19 05:43:07 +00:00
|
|
|
return HttpResponse(output)
|
|
|
|
|
2014-09-17 12:37:27 +00:00
|
|
|
# Leave the rest of the views (detail, results, vote) unchanged
|
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
There's a problem here, though: the page's design is hard-coded in the view. If
|
2005-07-19 05:43:07 +00:00
|
|
|
you want to change the way the page looks, you'll have to edit this Python code.
|
2013-02-07 10:51:25 +00:00
|
|
|
So let's use Django's template system to separate the design from Python by
|
|
|
|
creating a template that the view can use.
|
|
|
|
|
|
|
|
First, create a directory called ``templates`` in your ``polls`` directory.
|
|
|
|
Django will look for templates in there.
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
Your project's :setting:`TEMPLATES` setting describes how Django will load and
|
|
|
|
render templates. The default settings file configures a ``DjangoTemplates``
|
|
|
|
backend whose :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` option is set to
|
|
|
|
``True``. By convention ``DjangoTemplates`` looks for a "templates"
|
2015-05-11 23:43:40 +00:00
|
|
|
subdirectory in each of the :setting:`INSTALLED_APPS`.
|
2013-02-07 10:51:25 +00:00
|
|
|
|
|
|
|
Within the ``templates`` directory you have just created, create another
|
|
|
|
directory called ``polls``, and within that create a file called
|
|
|
|
``index.html``. In other words, your template should be at
|
|
|
|
``polls/templates/polls/index.html``. Because of how the ``app_directories``
|
|
|
|
template loader works as described above, you can refer to this template within
|
|
|
|
Django simply as ``polls/index.html``.
|
|
|
|
|
|
|
|
.. admonition:: Template namespacing
|
|
|
|
|
|
|
|
Now we *might* be able to get away with putting our templates directly in
|
|
|
|
``polls/templates`` (rather than creating another ``polls`` subdirectory),
|
|
|
|
but it would actually be a bad idea. Django will choose the first template
|
|
|
|
it finds whose name matches, and if you had a template with the same name
|
|
|
|
in a *different* application, Django would be unable to distinguish between
|
|
|
|
them. We need to be able to point Django at the right one, and the easiest
|
|
|
|
way to ensure this is by *namespacing* them. That is, by putting those
|
|
|
|
templates inside *another* directory named for the application itself.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Put the following code in that template:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
|
|
|
:caption: polls/templates/polls/index.html
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
{% if latest_question_list %}
|
2005-07-19 05:43:07 +00:00
|
|
|
<ul>
|
2013-09-06 18:57:00 +00:00
|
|
|
{% for question in latest_question_list %}
|
|
|
|
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
|
2005-07-19 05:43:07 +00:00
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
{% else %}
|
|
|
|
<p>No polls are available.</p>
|
|
|
|
{% endif %}
|
|
|
|
|
2013-09-23 22:23:47 +00:00
|
|
|
Now let's update our ``index`` view in ``polls/views.py`` to use the template:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2012-10-13 18:37:39 +00:00
|
|
|
|
|
|
|
from django.http import HttpResponse
|
2015-12-23 21:14:27 +00:00
|
|
|
from django.template import loader
|
2012-10-13 18:37:39 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Question
|
2013-09-06 18:57:00 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
|
|
|
|
def index(request):
|
2013-09-06 18:57:00 +00:00
|
|
|
latest_question_list = Question.objects.order_by('-pub_date')[:5]
|
2012-10-13 18:37:39 +00:00
|
|
|
template = loader.get_template('polls/index.html')
|
2015-12-23 21:14:27 +00:00
|
|
|
context = {
|
2013-09-06 18:57:00 +00:00
|
|
|
'latest_question_list': latest_question_list,
|
2015-12-23 21:14:27 +00:00
|
|
|
}
|
|
|
|
return HttpResponse(template.render(context, request))
|
2012-10-13 18:37:39 +00:00
|
|
|
|
|
|
|
That code loads the template called ``polls/index.html`` and passes it a
|
|
|
|
context. The context is a dictionary mapping template variable names to Python
|
|
|
|
objects.
|
|
|
|
|
2013-02-07 10:51:25 +00:00
|
|
|
Load the page by pointing your browser at "/polls/", and you should see a
|
2015-05-11 23:43:40 +00:00
|
|
|
bulleted-list containing the "What's up" question from :doc:`Tutorial 2
|
|
|
|
</intro/tutorial02>`. The link points to the question's detail page.
|
2012-10-30 19:53:56 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
A shortcut: :func:`~django.shortcuts.render`
|
|
|
|
--------------------------------------------
|
2005-09-23 22:50:05 +00:00
|
|
|
|
|
|
|
It's a very common idiom to load a template, fill a context and return an
|
2008-08-23 22:25:40 +00:00
|
|
|
:class:`~django.http.HttpResponse` object with the result of the rendered
|
|
|
|
template. Django provides a shortcut. Here's the full ``index()`` view,
|
2013-09-23 22:23:47 +00:00
|
|
|
rewritten:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
from django.shortcuts import render
|
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Question
|
2013-09-06 18:57:00 +00:00
|
|
|
|
2005-09-23 22:50:05 +00:00
|
|
|
|
|
|
|
def index(request):
|
2014-11-17 17:10:50 +00:00
|
|
|
latest_question_list = Question.objects.order_by('-pub_date')[:5]
|
2013-09-06 18:57:00 +00:00
|
|
|
context = {'latest_question_list': latest_question_list}
|
2012-10-13 18:37:39 +00:00
|
|
|
return render(request, 'polls/index.html', context)
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Note that once we've done this in all these views, we no longer need to import
|
2015-12-23 21:14:27 +00:00
|
|
|
:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
|
|
|
|
want to keep ``HttpResponse`` if you still have the stub methods for ``detail``,
|
|
|
|
``results``, and ``vote``).
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
The :func:`~django.shortcuts.render` function takes the request object as its
|
|
|
|
first argument, a template name as its second argument and a dictionary as its
|
|
|
|
optional third argument. It returns an :class:`~django.http.HttpResponse`
|
|
|
|
object of the given template rendered with the given context.
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Raising a 404 error
|
|
|
|
===================
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
Now, let's tackle the question detail view -- the page that displays the question text
|
2013-09-23 22:23:47 +00:00
|
|
|
for a given poll. Here's the view:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django.http import Http404
|
2013-05-18 11:34:29 +00:00
|
|
|
from django.shortcuts import render
|
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Question
|
2006-05-02 01:31:56 +00:00
|
|
|
# ...
|
2013-09-06 18:57:00 +00:00
|
|
|
def detail(request, question_id):
|
2005-07-19 05:43:07 +00:00
|
|
|
try:
|
2013-09-06 18:57:00 +00:00
|
|
|
question = Question.objects.get(pk=question_id)
|
|
|
|
except Question.DoesNotExist:
|
2015-01-13 08:02:17 +00:00
|
|
|
raise Http404("Question does not exist")
|
2013-09-06 18:57:00 +00:00
|
|
|
return render(request, 'polls/detail.html', {'question': question})
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The new concept here: The view raises the :exc:`~django.http.Http404` exception
|
2013-09-06 18:57:00 +00:00
|
|
|
if a question with the requested ID doesn't exist.
|
2005-07-19 05:43:07 +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
|
|
|
We'll discuss what you could put in that ``polls/detail.html`` template a bit
|
2013-02-24 03:06:04 +00:00
|
|
|
later, but if you'd like to quickly get the above example working, a file
|
2013-09-23 22:23:47 +00:00
|
|
|
containing just:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
|
|
|
:caption: polls/templates/polls/detail.html
|
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
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
{{ question }}
|
2009-06-17 13:46:52 +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
|
|
|
will get you started for now.
|
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
A shortcut: :func:`~django.shortcuts.get_object_or_404`
|
|
|
|
-------------------------------------------------------
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2011-09-30 10:28:39 +00:00
|
|
|
It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
|
|
|
|
and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
|
2013-09-23 22:23:47 +00:00
|
|
|
provides a shortcut. Here's the ``detail()`` view, rewritten:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/views.py
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2014-08-02 01:32:53 +00:00
|
|
|
from django.shortcuts import get_object_or_404, render
|
2013-05-18 11:34:29 +00:00
|
|
|
|
2015-02-22 14:59:56 +00:00
|
|
|
from .models import Question
|
2006-05-02 01:31:56 +00:00
|
|
|
# ...
|
2013-09-06 18:57:00 +00:00
|
|
|
def detail(request, question_id):
|
|
|
|
question = get_object_or_404(Question, pk=question_id)
|
|
|
|
return render(request, 'polls/detail.html', {'question': question})
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
|
2009-07-28 14:38:11 +00:00
|
|
|
as its first argument and an arbitrary number of keyword arguments, which it
|
2012-05-11 10:43:43 +00:00
|
|
|
passes to the :meth:`~django.db.models.query.QuerySet.get` function of the
|
|
|
|
model's manager. It raises :exc:`~django.http.Http404` if the object doesn't
|
|
|
|
exist.
|
2005-09-23 22:50:05 +00:00
|
|
|
|
|
|
|
.. admonition:: Philosophy
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
|
|
|
|
instead of automatically catching the
|
|
|
|
:exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
|
|
|
|
level, or having the model API raise :exc:`~django.http.Http404` instead of
|
|
|
|
:exc:`~django.core.exceptions.ObjectDoesNotExist`?
|
2005-09-23 22:50:05 +00:00
|
|
|
|
|
|
|
Because that would couple the model layer to the view layer. One of the
|
2012-10-13 18:37:39 +00:00
|
|
|
foremost design goals of Django is to maintain loose coupling. Some
|
|
|
|
controlled coupling is introduced in the :mod:`django.shortcuts` module.
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
|
|
|
|
just as :func:`~django.shortcuts.get_object_or_404` -- except using
|
2011-09-30 10:28:39 +00:00
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` instead of
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`. It raises
|
|
|
|
:exc:`~django.http.Http404` if the list is empty.
|
2005-09-23 22:50:05 +00:00
|
|
|
|
2005-07-19 05:43:07 +00:00
|
|
|
Use the template system
|
|
|
|
=======================
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Back to the ``detail()`` view for our poll application. Given the context
|
2013-09-06 18:57:00 +00:00
|
|
|
variable ``question``, here's what the ``polls/detail.html`` template might look
|
2008-08-23 22:25:40 +00:00
|
|
|
like:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
|
|
|
:caption: polls/templates/polls/detail.html
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<h1>{{ question.question_text }}</h1>
|
2005-07-19 05:43:07 +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 }}</li>
|
2005-07-19 05:43:07 +00:00
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
|
|
|
|
The template system uses dot-lookup syntax to access variable attributes. In
|
2013-09-06 18:57:00 +00:00
|
|
|
the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
|
|
|
|
on the object ``question``. Failing that, it tries an attribute lookup -- which
|
2011-01-13 13:47:21 +00:00
|
|
|
works, in this case. If attribute lookup had failed, it would've tried a
|
|
|
|
list-index lookup.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2011-10-03 08:06:01 +00:00
|
|
|
Method-calling happens in the :ttag:`{% for %}<for>` loop:
|
2013-09-06 18:57:00 +00:00
|
|
|
``question.choice_set.all`` is interpreted as the Python code
|
|
|
|
``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
|
2011-10-03 08:06:01 +00:00
|
|
|
suitable for use in the :ttag:`{% for %}<for>` tag.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
See the :doc:`template guide </topics/templates>` for more about templates.
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Removing hardcoded URLs in templates
|
|
|
|
====================================
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
Remember, when we wrote the link to a question in the ``polls/index.html``
|
2012-10-13 18:37:39 +00:00
|
|
|
template, the link was partially hardcoded like this:
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
.. code-block:: html+django
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
The problem with this hardcoded, tightly-coupled approach is that it becomes
|
|
|
|
challenging to change URLs on projects with a lot of templates. However, since
|
2016-10-20 17:29:04 +00:00
|
|
|
you defined the name argument in the :func:`~django.urls.path` functions in
|
2012-10-13 18:37:39 +00:00
|
|
|
the ``polls.urls`` module, you can remove a reliance on specific URL paths
|
|
|
|
defined in your url configurations by using the ``{% url %}`` template tag:
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
.. code-block:: html+django
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
The way this works is by looking up the URL definition as specified in the
|
|
|
|
``polls.urls`` module. You can see exactly where the URL name of 'detail' is
|
|
|
|
defined below::
|
2010-11-06 10:06:30 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
...
|
|
|
|
# the 'name' value as called by the {% url %} template tag
|
2016-10-20 17:29:04 +00:00
|
|
|
path('<int:question_id>/', views.detail, name='detail'),
|
2012-10-13 18:37:39 +00:00
|
|
|
...
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
If you want to change the URL of the polls detail view to something else,
|
|
|
|
perhaps to something like ``polls/specifics/12/`` instead of doing it in the
|
|
|
|
template (or templates) you would change it in ``polls/urls.py``::
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
...
|
|
|
|
# added the word 'specifics'
|
2016-10-20 17:29:04 +00:00
|
|
|
path('specifics/<int:question_id>/', views.detail, name='detail'),
|
2012-10-13 18:37:39 +00:00
|
|
|
...
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Namespacing URL names
|
2019-02-08 20:38:30 +00:00
|
|
|
=====================
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
The tutorial project has just one app, ``polls``. In real Django projects,
|
|
|
|
there might be five, ten, twenty apps or more. How does Django differentiate
|
|
|
|
the URL names between them? For example, the ``polls`` app has a ``detail``
|
|
|
|
view, and so might an app on the same project that is for a blog. How does one
|
|
|
|
make it so that Django knows which app view to create for a url when using the
|
|
|
|
``{% url %}`` template tag?
|
|
|
|
|
2015-05-28 15:25:52 +00:00
|
|
|
The answer is to add namespaces to your URLconf. In the ``polls/urls.py``
|
|
|
|
file, go ahead and add an ``app_name`` to set the application namespace:
|
2013-09-23 22:23:47 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: polls/urls.py
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
from django.urls import path
|
2011-09-11 22:36:16 +00:00
|
|
|
|
2016-01-02 09:55:48 +00:00
|
|
|
from . import views
|
|
|
|
|
2015-05-28 15:25:52 +00:00
|
|
|
app_name = 'polls'
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('', views.index, name='index'),
|
|
|
|
path('<int:question_id>/', views.detail, name='detail'),
|
|
|
|
path('<int:question_id>/results/', views.results, name='results'),
|
|
|
|
path('<int:question_id>/vote/', views.vote, name='vote'),
|
2014-04-02 00:46:34 +00:00
|
|
|
]
|
2005-07-19 05:43:07 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
Now change your ``polls/index.html`` template from:
|
2012-07-29 22:14:26 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
|
|
|
:caption: polls/templates/polls/index.html
|
2012-07-29 22:14:26 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
|
2012-07-29 22:14:26 +00:00
|
|
|
|
2012-10-13 18:37:39 +00:00
|
|
|
to point at the namespaced detail view:
|
2012-07-29 22:14:26 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: html+django
|
|
|
|
:caption: polls/templates/polls/index.html
|
2012-07-29 22:14:26 +00:00
|
|
|
|
2013-09-06 18:57:00 +00:00
|
|
|
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
|
2012-08-18 07:55:13 +00:00
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
When you're comfortable with writing views, read :doc:`part 4 of this tutorial
|
|
|
|
</intro/tutorial04>` to learn about simple form processing and generic views.
|