2005-07-19 13:43:07 +08:00
|
|
|
=====================================
|
|
|
|
Writing your first Django app, part 3
|
|
|
|
=====================================
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
|
2008-08-24 06:25:40 +08:00
|
|
|
continuing the Web-poll application and will focus on creating the public
|
|
|
|
interface -- "views."
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
Philosophy
|
|
|
|
==========
|
2005-07-22 01:59:05 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
A view is a "type" of Web page in your Django application that generally serves
|
2010-10-09 16:12:50 +08:00
|
|
|
a specific function and has a specific template. For example, in a Weblog
|
2005-08-08 23:47:57 +08:00
|
|
|
application, you might have the following views:
|
2005-07-23 02:45:22 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Blog homepage -- displays the latest few entries.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Entry "detail" page -- permalink page for a single entry.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Year-based archive page -- displays all months with entries in the
|
2005-08-09 05:04:32 +08:00
|
|
|
given year.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Month-based archive page -- displays all days with entries in the
|
2005-08-09 05:04:32 +08:00
|
|
|
given month.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Day-based archive page -- displays all entries in the given day.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Comment action -- handles posting comments to a given entry.
|
2005-07-23 02:45:22 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
In our poll application, we'll have the following four views:
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-12-28 07:29:49 +08:00
|
|
|
* Poll "index" page -- displays the latest few polls.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Poll "detail" page -- displays a poll question, with no results but
|
2005-08-09 05:04:32 +08:00
|
|
|
with a form to vote.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Poll "results" page -- displays results for a particular poll.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
* Vote action -- handles voting for a particular choice in a particular
|
2005-08-09 05:04:32 +08:00
|
|
|
poll.
|
2005-08-02 03:02:55 +08:00
|
|
|
|
2005-08-08 23:47:57 +08:00
|
|
|
In Django, each view is represented by a simple Python function.
|
2005-08-02 03:02:55 +08:00
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
Design your URLs
|
|
|
|
================
|
|
|
|
|
|
|
|
The first step of writing views is to design your URL structure. You do this by
|
|
|
|
creating a Python module, called a URLconf. URLconfs are how Django associates
|
|
|
|
a given URL with given Python code.
|
|
|
|
|
|
|
|
When a user requests a Django-powered page, the system looks at the
|
2008-08-24 06:25:40 +08:00
|
|
|
:setting:`ROOT_URLCONF` setting, which contains a string in Python dotted
|
|
|
|
syntax. Django loads that module and looks for a module-level variable called
|
2005-07-19 13:43:07 +08:00
|
|
|
``urlpatterns``, which is a sequence of tuples in the following format::
|
|
|
|
|
|
|
|
(regular expression, Python callback function [, optional dictionary])
|
|
|
|
|
|
|
|
Django starts at the first regular expression and makes its way down the list,
|
|
|
|
comparing the requested URL against each regular expression until it finds one
|
|
|
|
that matches.
|
|
|
|
|
|
|
|
When it finds a match, Django calls the Python callback function, with an
|
2008-08-24 06:25:40 +08:00
|
|
|
:class:`~django.http.HttpRequest` object as the first argument, any "captured"
|
|
|
|
values from the regular expression as keyword arguments, and, optionally,
|
|
|
|
arbitrary keyword arguments from the dictionary (an optional third item in the
|
|
|
|
tuple).
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
For more on :class:`~django.http.HttpRequest` objects, see the
|
2010-08-20 03:27:44 +08:00
|
|
|
:doc:`/ref/request-response`. For more details on URLconfs, see the
|
|
|
|
:doc:`/topics/http/urls`.
|
2005-09-03 01:41:40 +08:00
|
|
|
|
2009-06-18 21:32:12 +08:00
|
|
|
When you ran ``django-admin.py startproject mysite`` at the beginning of
|
2006-05-02 09:31:56 +08:00
|
|
|
Tutorial 1, it created a default URLconf in ``mysite/urls.py``. It also
|
2008-08-24 06:25:40 +08:00
|
|
|
automatically set your :setting:`ROOT_URLCONF` setting (in ``settings.py``) to
|
|
|
|
point at that file::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
ROOT_URLCONF = 'mysite.urls'
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Time for an example. Edit ``mysite/urls.py`` so it looks like this::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
|
|
|
|
2009-06-17 21:46:52 +08:00
|
|
|
from django.contrib import admin
|
|
|
|
admin.autodiscover()
|
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
urlpatterns = patterns('',
|
2010-10-09 15:45:52 +08:00
|
|
|
(r'^polls/$', 'polls.views.index'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
|
2009-05-09 23:52:17 +08:00
|
|
|
(r'^admin/', include(admin.site.urls)),
|
2005-07-19 13:43:07 +08:00
|
|
|
)
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
This is worth a review. When somebody requests a page from your Web site -- say,
|
|
|
|
"/polls/23/", Django will load this Python module, because it's pointed to by
|
|
|
|
the :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``
|
2005-07-19 13:52:06 +08:00
|
|
|
and traverses the regular expressions in order. When it finds a regular
|
2006-05-02 09:31:56 +08:00
|
|
|
expression that matches -- ``r'^polls/(?P<poll_id>\d+)/$'`` -- it loads the
|
2010-10-09 15:45:52 +08:00
|
|
|
function ``detail()`` from ``polls/views.py``. Finally, it calls that
|
|
|
|
``detail()`` function like so::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-11-20 02:20:30 +08:00
|
|
|
detail(request=<HttpRequest object>, poll_id='23')
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-02-22 10:29:39 +08:00
|
|
|
The ``poll_id='23'`` part comes from ``(?P<poll_id>\d+)``. Using parentheses
|
2008-08-24 06:25:40 +08:00
|
|
|
around a pattern "captures" the text matched by that pattern and sends it as an
|
|
|
|
argument to the view function; the ``?P<poll_id>`` defines the name that will be
|
|
|
|
used to identify the matched pattern; and ``\d+`` is a regular expression to
|
|
|
|
match a sequence of digits (i.e., a number).
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Because the URL patterns are regular expressions, there really is no limit on
|
2008-08-24 06:25:40 +08:00
|
|
|
what you can do with them. And there's no need to add URL cruft such as ``.php``
|
|
|
|
-- unless you have a sick sense of humor, in which case you can do something
|
|
|
|
like this::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
(r'^polls/latest\.php$', 'polls.views.index'),
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-11-16 10:00:23 +08:00
|
|
|
But, don't do that. It's silly.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-11-20 02:20:30 +08:00
|
|
|
Note that these regular expressions do not search GET and POST parameters, or
|
|
|
|
the domain name. For example, in a request to ``http://www.example.com/myapp/``,
|
2009-04-01 07:34:03 +08:00
|
|
|
the URLconf will look for ``myapp/``. In a request to
|
|
|
|
``http://www.example.com/myapp/?page=3``, the URLconf will look for ``myapp/``.
|
2005-11-20 02:20:30 +08:00
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
If you need help with regular expressions, see `Wikipedia's entry`_ and the
|
2008-08-24 06:25:40 +08:00
|
|
|
`Python documentation`_. Also, the O'Reilly book "Mastering Regular Expressions"
|
|
|
|
by Jeffrey Friedl is fantastic.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-05-15 19:33:17 +08:00
|
|
|
Finally, a performance note: these regular expressions are compiled the first
|
2005-07-19 13:43:07 +08:00
|
|
|
time the URLconf module is loaded. They're super fast.
|
|
|
|
|
|
|
|
.. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
|
2008-11-02 03:02:09 +08:00
|
|
|
.. _Python documentation: http://docs.python.org/library/re.html
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Write your first view
|
|
|
|
=====================
|
|
|
|
|
|
|
|
Well, we haven't created any views yet -- we just have the URLconf. But let's
|
|
|
|
make sure Django is following the URLconf properly.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Fire up the Django development Web server:
|
|
|
|
|
|
|
|
.. code-block:: bash
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-01-11 10:06:27 +08:00
|
|
|
python manage.py runserver
|
2005-08-02 03:02:55 +08:00
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
Now go to "http://localhost:8000/polls/" on your domain in your Web browser.
|
2005-11-16 10:00:23 +08:00
|
|
|
You should get a pleasantly-colored error page with the following message::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-11-16 10:00:23 +08:00
|
|
|
ViewDoesNotExist at /polls/
|
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
Tried index in module polls.views. Error was: 'module'
|
2005-11-16 10:00:23 +08:00
|
|
|
object has no attribute 'index'
|
|
|
|
|
|
|
|
This error happened because you haven't written a function ``index()`` in the
|
2010-10-09 15:45:52 +08:00
|
|
|
module ``polls/views.py``.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Try "/polls/23/", "/polls/23/results/" and "/polls/23/vote/". The error
|
2005-11-16 10:00:23 +08:00
|
|
|
messages tell you which view Django tried (and failed to find, because you
|
|
|
|
haven't written any views yet).
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
Time to write the first view. Open the file ``polls/views.py``
|
2005-07-19 13:43:07 +08:00
|
|
|
and put the following Python code in it::
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import HttpResponse
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
def index(request):
|
|
|
|
return HttpResponse("Hello, world. You're at the poll index.")
|
|
|
|
|
2005-07-21 23:36:43 +08:00
|
|
|
This is the simplest view possible. Go to "/polls/" in your browser, and you
|
|
|
|
should see your text.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2009-10-14 21:38:31 +08:00
|
|
|
Now lets add a few more views. These views are slightly different, because
|
|
|
|
they take an argument (which, remember, is passed in from whatever was
|
|
|
|
captured by the regular expression in the URLconf)::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
def detail(request, poll_id):
|
|
|
|
return HttpResponse("You're looking at poll %s." % poll_id)
|
|
|
|
|
2009-10-14 21:38:31 +08:00
|
|
|
def results(request, poll_id):
|
|
|
|
return HttpResponse("You're looking at the results of poll %s." % poll_id)
|
|
|
|
|
|
|
|
def vote(request, poll_id):
|
|
|
|
return HttpResponse("You're voting on poll %s." % poll_id)
|
|
|
|
|
|
|
|
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.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Write views that actually do something
|
|
|
|
======================================
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Each view is responsible for doing one of two things: Returning an
|
|
|
|
: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 13:43:07 +08: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-24 06:25:40 +08:00
|
|
|
All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Because it's convenient, let's use Django's own database API, which we covered
|
2010-08-20 03:27:44 +08:00
|
|
|
in :doc:`Tutorial 1 </intro/tutorial01>`. Here's one stab at the ``index()``
|
2008-08-24 06:25:40 +08:00
|
|
|
view, which displays the latest 5 poll questions in the system, separated by
|
|
|
|
commas, according to publication date::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
from polls.models import Poll
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import HttpResponse
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
def index(request):
|
2006-07-19 09:35:58 +08:00
|
|
|
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
|
2005-07-19 13:43:07 +08:00
|
|
|
output = ', '.join([p.question for p in latest_poll_list])
|
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
There's a problem here, though: The page's design is hard-coded in the view. If
|
|
|
|
you want to change the way the page looks, you'll have to edit this Python code.
|
|
|
|
So let's use Django's template system to separate the design from Python::
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.template import Context, loader
|
2010-10-09 15:45:52 +08:00
|
|
|
from polls.models import Poll
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import HttpResponse
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
def index(request):
|
2006-07-19 09:35:58 +08:00
|
|
|
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
|
2006-05-02 09:31:56 +08:00
|
|
|
t = loader.get_template('polls/index.html')
|
2005-09-24 06:50:05 +08:00
|
|
|
c = Context({
|
2005-07-19 13:43:07 +08:00
|
|
|
'latest_poll_list': latest_poll_list,
|
|
|
|
})
|
|
|
|
return HttpResponse(t.render(c))
|
|
|
|
|
2008-08-24 06:25:40 +08: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.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-07-19 13:58:19 +08:00
|
|
|
Reload the page. Now you'll see an error::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-05-31 22:29:11 +08:00
|
|
|
TemplateDoesNotExist at /polls/
|
|
|
|
polls/index.html
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Ah. There's no template yet. First, create a directory, somewhere on your
|
2008-08-24 06:25:40 +08:00
|
|
|
filesystem, whose contents Django can access. (Django runs as whatever user your
|
|
|
|
server runs.) Don't put them under your document root, though. You probably
|
|
|
|
shouldn't make them public, just for security's sake.
|
|
|
|
Then edit :setting:`TEMPLATE_DIRS` in your ``settings.py`` to tell Django where
|
|
|
|
it can find templates -- just as you did in the "Customize the admin look and
|
|
|
|
feel" section of Tutorial 2.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
When you've done that, create a directory ``polls`` in your template directory.
|
2006-05-02 09:31:56 +08:00
|
|
|
Within that, create a file called ``index.html``. Note that our
|
|
|
|
``loader.get_template('polls/index.html')`` code from above maps to
|
2005-07-19 13:43:07 +08:00
|
|
|
"[template_directory]/polls/index.html" on the filesystem.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Put the following code in that template:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
{% if latest_poll_list %}
|
|
|
|
<ul>
|
|
|
|
{% for poll in latest_poll_list %}
|
2010-02-25 06:11:49 +08:00
|
|
|
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
|
2005-07-19 13:43:07 +08:00
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
{% else %}
|
|
|
|
<p>No polls are available.</p>
|
|
|
|
{% endif %}
|
|
|
|
|
2005-07-21 23:36:43 +08:00
|
|
|
Load the page in your Web browser, and you should see a bulleted-list
|
2010-02-23 23:00:33 +08:00
|
|
|
containing the "What's up" poll from Tutorial 1. The link points to the poll's
|
|
|
|
detail page.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2005-09-24 06:50:05 +08:00
|
|
|
A shortcut: render_to_response()
|
|
|
|
--------------------------------
|
|
|
|
|
|
|
|
It's a very common idiom to load a template, fill a context and return an
|
2008-08-24 06:25:40 +08:00
|
|
|
:class:`~django.http.HttpResponse` object with the result of the rendered
|
|
|
|
template. Django provides a shortcut. Here's the full ``index()`` view,
|
|
|
|
rewritten::
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.shortcuts import render_to_response
|
2010-10-09 15:45:52 +08:00
|
|
|
from polls.models import Poll
|
2005-09-24 06:50:05 +08:00
|
|
|
|
|
|
|
def index(request):
|
2006-10-23 15:42:04 +08:00
|
|
|
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
|
2006-05-02 09:31:56 +08:00
|
|
|
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Note that once we've done this in all these views, we no longer need to import
|
|
|
|
:mod:`~django.template.loader`, :class:`~django.template.Context` and
|
|
|
|
:class:`~django.http.HttpResponse`.
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The :func:`~django.shortcuts.render_to_response` function takes a template name
|
|
|
|
as its first argument and a dictionary as its optional second argument. It
|
|
|
|
returns an :class:`~django.http.HttpResponse` object of the given template
|
|
|
|
rendered with the given context.
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
Raising 404
|
|
|
|
===========
|
|
|
|
|
|
|
|
Now, let's tackle the poll detail view -- the page that displays the question
|
|
|
|
for a given poll. Here's the view::
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import Http404
|
|
|
|
# ...
|
2005-07-19 13:43:07 +08:00
|
|
|
def detail(request, poll_id):
|
|
|
|
try:
|
2006-05-02 09:31:56 +08:00
|
|
|
p = Poll.objects.get(pk=poll_id)
|
|
|
|
except Poll.DoesNotExist:
|
2005-07-19 13:43:07 +08:00
|
|
|
raise Http404
|
2006-05-02 09:31:56 +08:00
|
|
|
return render_to_response('polls/detail.html', {'poll': p})
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The new concept here: The view raises the :exc:`~django.http.Http404` exception
|
|
|
|
if a poll with the requested ID doesn't exist.
|
2005-07-19 13:43:07 +08: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-04 02:30:54 +08:00
|
|
|
We'll discuss what you could put in that ``polls/detail.html`` template a bit
|
|
|
|
later, but if you'd like to quickly get the above example working, just::
|
|
|
|
|
|
|
|
{{ poll }}
|
2009-06-17 21:46:52 +08: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-04 02:30:54 +08:00
|
|
|
will get you started for now.
|
|
|
|
|
2005-09-24 06:50:05 +08:00
|
|
|
A shortcut: get_object_or_404()
|
|
|
|
-------------------------------
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
It's a very common idiom to use :meth:`~django.db.models.QuerySet.get` and raise
|
|
|
|
:exc:`~django.http.Http404` if the object doesn't exist. Django provides a
|
|
|
|
shortcut. Here's the ``detail()`` view, rewritten::
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.shortcuts import render_to_response, get_object_or_404
|
|
|
|
# ...
|
2005-09-24 06:50:05 +08:00
|
|
|
def detail(request, poll_id):
|
2006-05-02 09:31:56 +08:00
|
|
|
p = get_object_or_404(Poll, pk=poll_id)
|
|
|
|
return render_to_response('polls/detail.html', {'poll': p})
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
|
2009-07-28 22:38:11 +08:00
|
|
|
as its first argument and an arbitrary number of keyword arguments, which it
|
|
|
|
passes to the module's :meth:`~django.db.models.QuerySet.get` function. It
|
2008-08-24 06:25:40 +08:00
|
|
|
raises :exc:`~django.http.Http404` if the object doesn't exist.
|
2005-09-24 06:50:05 +08:00
|
|
|
|
|
|
|
.. admonition:: Philosophy
|
|
|
|
|
2008-08-24 06:25:40 +08: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-24 06:50:05 +08:00
|
|
|
|
|
|
|
Because that would couple the model layer to the view layer. One of the
|
|
|
|
foremost design goals of Django is to maintain loose coupling.
|
|
|
|
|
2008-08-24 06:25:40 +08: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
|
|
|
|
:meth:`~django.db.models.QuerySet.filter` instead of
|
|
|
|
:meth:`~django.db.models.QuerySet.get`. It raises :exc:`~django.http.Http404` if
|
|
|
|
the list is empty.
|
2005-09-24 06:50:05 +08:00
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
Write a 404 (page not found) view
|
|
|
|
=================================
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
When you raise :exc:`~django.http.Http404` from within a view, Django will load
|
|
|
|
a special view devoted to handling 404 errors. It finds it by looking for the
|
|
|
|
variable ``handler404``, which is a string in Python dotted syntax -- the same
|
|
|
|
format the normal URLconf callbacks use. A 404 view itself has nothing special:
|
|
|
|
It's just a normal view.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
You normally won't have to bother with writing 404 views. By default, URLconfs
|
|
|
|
have the following line up top::
|
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
|
|
|
|
|
|
|
That takes care of setting ``handler404`` in the current module. As you can see
|
|
|
|
in ``django/conf/urls/defaults.py``, ``handler404`` is set to
|
2008-08-24 06:25:40 +08:00
|
|
|
:func:`django.views.defaults.page_not_found` by default.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2009-07-15 21:53:29 +08:00
|
|
|
Four more things to note about 404 views:
|
2005-07-19 13:43:07 +08: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-04 02:30:54 +08:00
|
|
|
* If :setting:`DEBUG` is set to ``True`` (in your settings module) then your
|
|
|
|
404 view will never be used (and thus the ``404.html`` template will never
|
|
|
|
be rendered) because the traceback will be displayed instead.
|
|
|
|
|
2005-07-22 01:59:05 +08:00
|
|
|
* The 404 view is also called if Django doesn't find a match after checking
|
|
|
|
every regular expression in the URLconf.
|
2009-06-17 21:46:52 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
* If you don't define your own 404 view -- and simply use the default, which
|
|
|
|
is recommended -- you still have one obligation: To create a ``404.html``
|
|
|
|
template in the root of your template directory. The default 404 view will
|
|
|
|
use that template for all 404 errors.
|
2009-06-17 21:46:52 +08: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-04 02:30:54 +08:00
|
|
|
* If :setting:`DEBUG` is set to ``False`` (in your settings module) and if
|
|
|
|
you didn't create a ``404.html`` file, an ``Http500`` is raised instead.
|
|
|
|
So remember to create a ``404.html``.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Write a 500 (server error) view
|
|
|
|
===============================
|
|
|
|
|
|
|
|
Similarly, URLconfs may define a ``handler500``, which points to a view to call
|
|
|
|
in case of server errors. Server errors happen when you have runtime errors in
|
|
|
|
view code.
|
|
|
|
|
|
|
|
Use the template system
|
|
|
|
=======================
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Back to the ``detail()`` view for our poll application. Given the context
|
2007-08-05 12:39:52 +08:00
|
|
|
variable ``poll``, here's what the "polls/detail.html" template might look
|
2008-08-24 06:25:40 +08:00
|
|
|
like:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
<h1>{{ poll.question }}</h1>
|
|
|
|
<ul>
|
2006-05-02 09:31:56 +08:00
|
|
|
{% for choice in poll.choice_set.all %}
|
2005-07-19 13:43:07 +08:00
|
|
|
<li>{{ choice.choice }}</li>
|
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
|
|
|
|
The template system uses dot-lookup syntax to access variable attributes. In
|
|
|
|
the example of ``{{ poll.question }}``, first Django does a dictionary lookup
|
2011-01-13 21:47:21 +08:00
|
|
|
on the object ``poll``. Failing that, it tries an attribute lookup -- which
|
|
|
|
works, in this case. If attribute lookup had failed, it would've tried a
|
|
|
|
list-index lookup.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Method-calling happens in the ``{% for %}`` loop: ``poll.choice_set.all`` is
|
|
|
|
interpreted as the Python code ``poll.choice_set.all()``, which returns an
|
|
|
|
iterable of Choice objects and is suitable for use in the ``{% for %}`` tag.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
See the :doc:`template guide </topics/templates>` for more about templates.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Simplifying the URLconfs
|
|
|
|
========================
|
|
|
|
|
|
|
|
Take some time to play around with the views and template system. As you edit
|
|
|
|
the URLconf, you may notice there's a fair bit of redundancy in it::
|
|
|
|
|
|
|
|
urlpatterns = patterns('',
|
2010-10-09 15:45:52 +08:00
|
|
|
(r'^polls/$', 'polls.views.index'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
|
2005-07-19 13:43:07 +08:00
|
|
|
)
|
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
Namely, ``polls.views`` is in every callback.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Because this is a common case, the URLconf framework provides a shortcut for
|
|
|
|
common prefixes. You can factor out the common prefixes and add them as the
|
2008-08-24 06:25:40 +08:00
|
|
|
first argument to :func:`~django.conf.urls.defaults.patterns`, like so::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
urlpatterns = patterns('polls.views',
|
2005-07-19 13:43:07 +08:00
|
|
|
(r'^polls/$', 'index'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/$', 'detail'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
|
|
|
|
)
|
|
|
|
|
|
|
|
This is functionally identical to the previous formatting. It's just a bit
|
|
|
|
tidier.
|
|
|
|
|
2010-11-06 18:06:30 +08:00
|
|
|
Since you generally don't want the prefix for one app to be applied to every
|
|
|
|
callback in your URLconf, you can concatenate multiple
|
|
|
|
:func:`~django.conf.urls.defaults.patterns`. Your full ``mysite/urls.py`` might
|
|
|
|
now look like this::
|
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
|
|
|
|
|
|
|
from django.contrib import admin
|
|
|
|
admin.autodiscover()
|
|
|
|
|
|
|
|
urlpatterns = patterns('polls.views',
|
|
|
|
(r'^polls/$', 'index'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/$', 'detail'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
|
|
|
|
(r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
|
|
|
|
)
|
|
|
|
|
|
|
|
urlpatterns += patterns('',
|
|
|
|
(r'^admin/', include(admin.site.urls)),
|
|
|
|
)
|
|
|
|
|
2005-07-19 13:43:07 +08:00
|
|
|
Decoupling the URLconfs
|
|
|
|
=======================
|
|
|
|
|
|
|
|
While we're at it, we should take the time to decouple our poll-app URLs from
|
|
|
|
our Django project configuration. Django apps are meant to be pluggable -- that
|
2008-08-24 06:25:40 +08:00
|
|
|
is, each particular app should be transferable to another Django installation
|
2005-07-19 13:43:07 +08:00
|
|
|
with minimal fuss.
|
|
|
|
|
|
|
|
Our poll app is pretty decoupled at this point, thanks to the strict directory
|
2006-01-11 10:06:27 +08:00
|
|
|
structure that ``python manage.py startapp`` created, but one part of it is
|
2005-07-19 13:43:07 +08:00
|
|
|
coupled to the Django settings: The URLconf.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
We've been editing the URLs in ``mysite/urls.py``, but the URL design of an
|
2005-10-19 09:09:05 +08:00
|
|
|
app is specific to the app, not to the Django installation -- so let's move the
|
|
|
|
URLs within the app directory.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
Copy the file ``mysite/urls.py`` to ``polls/urls.py``. Then, change
|
2008-08-24 06:25:40 +08:00
|
|
|
``mysite/urls.py`` to remove the poll-specific URLs and insert an
|
2010-11-06 18:06:30 +08:00
|
|
|
:func:`~django.conf.urls.defaults.include`, leaving you with::
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-09-14 06:47:20 +08:00
|
|
|
# This also imports the include function
|
|
|
|
from django.conf.urls.defaults import *
|
2010-11-06 18:06:30 +08:00
|
|
|
|
|
|
|
from django.contrib import admin
|
|
|
|
admin.autodiscover()
|
|
|
|
|
2009-06-18 21:36:40 +08:00
|
|
|
urlpatterns = patterns('',
|
2010-10-09 15:45:52 +08:00
|
|
|
(r'^polls/', include('polls.urls')),
|
2010-11-06 18:06:30 +08:00
|
|
|
(r'^admin/', include(admin.site.urls)),
|
2010-09-14 06:47:20 +08:00
|
|
|
)
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-11-06 18:06:30 +08:00
|
|
|
:func:`~django.conf.urls.defaults.include` simply references another URLconf.
|
2008-08-24 06:25:40 +08:00
|
|
|
Note that the regular expression doesn't have a ``$`` (end-of-string match
|
|
|
|
character) but has the trailing slash. Whenever Django encounters
|
|
|
|
:func:`~django.conf.urls.defaults.include`, it chops off whatever part of the
|
|
|
|
URL matched up to that point and sends the remaining string to the included
|
|
|
|
URLconf for further processing.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
|
|
|
Here's what happens if a user goes to "/polls/34/" in this system:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
* Django will find the match at ``'^polls/'``
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
* Then, Django will strip off the matching text (``"polls/"``) and send the
|
2010-10-09 15:45:52 +08:00
|
|
|
remaining text -- ``"34/"`` -- to the 'polls.urls' URLconf for
|
2008-08-24 06:25:40 +08:00
|
|
|
further processing.
|
|
|
|
|
2010-10-21 05:18:58 +08:00
|
|
|
Now that we've decoupled that, we need to decouple the ``polls.urls``
|
2009-06-18 21:32:12 +08:00
|
|
|
URLconf by removing the leading "polls/" from each line, and removing the
|
2011-05-22 08:12:48 +08:00
|
|
|
lines registering the admin site. Your ``polls/urls.py`` file should now look like
|
2010-10-21 05:18:58 +08:00
|
|
|
this::
|
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-10-09 15:45:52 +08:00
|
|
|
urlpatterns = patterns('polls.views',
|
2005-07-19 13:43:07 +08:00
|
|
|
(r'^$', 'index'),
|
|
|
|
(r'^(?P<poll_id>\d+)/$', 'detail'),
|
|
|
|
(r'^(?P<poll_id>\d+)/results/$', 'results'),
|
|
|
|
(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
|
|
|
|
)
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The idea behind :func:`~django.conf.urls.defaults.include` and URLconf
|
|
|
|
decoupling is to make it easy to plug-and-play URLs. Now that polls are in their
|
|
|
|
own URLconf, they can be placed under "/polls/", or under "/fun_polls/", or
|
2010-11-07 09:42:55 +08:00
|
|
|
under "/content/polls/", or any other path root, and the app will still work.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-11-07 09:42:55 +08:00
|
|
|
All the poll app cares about is its relative path, not its absolute path.
|
2005-07-19 13:43:07 +08:00
|
|
|
|
2010-08-20 03:27:44 +08: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.
|