Merge pull request #1129 from frog32/master

Add needed Imports to the Documentation
This commit is contained in:
Marc Tamlyn 2013-05-19 01:37:25 -07:00
commit 33c361ef9d
23 changed files with 211 additions and 35 deletions

View File

@ -197,6 +197,7 @@ answer newbie questions, and generally made Django that much better:
J. Clifford Dyer <jcd@sdf.lonestar.org>
Clint Ecker
Nick Efford <nick@efford.org>
Marc Egli <frog32@me.com>
eibaan@gmail.com
David Eklund
Julia Elman
@ -221,6 +222,7 @@ answer newbie questions, and generally made Django that much better:
Stefane Fermgier <sf@fermigier.com>
J. Pablo Fernandez <pupeno@pupeno.com>
Maciej Fijalkowski
Leandra Finger <leandra.finger@gmail.com>
Juan Pedro Fisanotti <fisadev@gmail.com>
Ben Firshman <ben@firshman.co.uk>
Matthew Flanagan <http://wadofstuff.blogspot.com>
@ -531,6 +533,7 @@ answer newbie questions, and generally made Django that much better:
Don Spaulding <donspauldingii@gmail.com>
Calvin Spealman <ironfroggy@gmail.com>
Dane Springmeyer
Silvan Spross <silvan.spross@gmail.com>
Bjørn Stabell <bjorn@exoweb.net>
Georgi Stanojevski <glisha@gmail.com>
starrynight <cmorgh@gmail.com>

View File

@ -24,6 +24,8 @@ representing your models -- so far, it's been solving two years' worth of
database-schema problems. Here's a quick example, which might be saved in
the file ``mysite/news/models.py``::
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
@ -214,6 +216,8 @@ Generally, a view retrieves data according to the parameters, loads a template
and renders the template with the retrieved data. Here's an example view for
``year_archive`` from above::
from django.shortcuts import render_to_response
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list})

View File

@ -582,6 +582,8 @@ of this object. Let's fix that by editing the polls model (in the
``Choice``. On Python 3, simply replace ``__unicode__`` by ``__str__`` in the
following example::
from django.db import models
class Poll(models.Model):
# ...
def __unicode__(self): # Python 3: def __str__(self):

View File

@ -158,6 +158,9 @@ you want when you register the object.
Let's see how this works by re-ordering the fields on the edit form. Replace
the ``admin.site.register(Poll)`` line with::
from django.contrib import admin
from polls.models import Poll
class PollAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question']
@ -179,6 +182,9 @@ of fields, choosing an intuitive order is an important usability detail.
And speaking of forms with dozens of fields, you might want to split the form
up into fieldsets::
from django.contrib import admin
from polls.models import Poll
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
@ -198,6 +204,9 @@ You can assign arbitrary HTML classes to each fieldset. Django provides a
This is useful when you have a long form that contains a number of fields that
aren't commonly used::
from django.contrib import admin
from polls.models import Poll
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
@ -218,6 +227,7 @@ Yet.
There are two ways to solve this problem. The first is to register ``Choice``
with the admin just as we did with ``Poll``. That's easy::
from django.contrib import admin
from polls.models import Choice
admin.site.register(Choice)
@ -342,6 +352,12 @@ representation of the output.
You can improve that by giving that method (in :file:`polls/models.py`) a few
attributes, as follows::
import datetime
from django.utils import timezone
from django.db import models
from polls.models import Poll
class Poll(models.Model):
# ...
def was_published_recently(self):

View File

@ -393,6 +393,9 @@ Now, let's tackle the poll detail view -- the page that displays the question
for a given poll. Here's the view::
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll
# ...
def detail(request, poll_id):
try:
@ -420,6 +423,8 @@ and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
provides a shortcut. Here's the ``detail()`` view, rewritten::
from django.shortcuts import render, get_object_or_404
from polls.models import Poll
# ...
def detail(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)

View File

@ -136,6 +136,8 @@ object. For more on :class:`~django.http.HttpRequest` objects, see the
After somebody votes in a poll, the ``vote()`` view redirects to the results
page for the poll. Let's write that view::
from django.shortcuts import get_object_or_404, render
def results(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/results.html', {'poll': poll})

View File

@ -98,6 +98,8 @@ second element is the human-readable name. For example::
Generally, it's best to define choices inside a model class, and to
define a suitably-named constant for each value::
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
@ -997,12 +999,15 @@ relationship with itself -- use ``models.ForeignKey('self')``.
If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::
from django.db import models
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
pass
To refer to models defined in another application, you can explicitly specify
a model with the full application label. For example, if the ``Manufacturer``
@ -1135,6 +1140,9 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
necessary to avoid executing queries at the time your models.py is
imported::
from django.db import models
from django.contrib.auth.models import User
def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]
@ -1207,6 +1215,8 @@ that control how the relationship functions.
Only used in the definition of ManyToManyFields on self. Consider the
following model::
from django.db import models
class Person(models.Model):
friends = models.ManyToManyField("self")

View File

@ -34,6 +34,8 @@ that, you need to :meth:`~Model.save()`.
1. Add a classmethod on the model class::
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
@ -105,6 +107,7 @@ individually.
You'll need to call ``full_clean`` manually when you want to run one-step model
validation for your own manually created models. For example::
from django.core.exceptions import ValidationError
try:
article.full_clean()
except ValidationError as e:
@ -132,6 +135,7 @@ automatically provide a value for a field, or to do validation that requires
access to more than a single field::
def clean(self):
import datetime
from django.core.exceptions import ValidationError
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
@ -434,6 +438,8 @@ representation of the model from the ``__unicode__()`` method.
For example::
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@ -460,6 +466,9 @@ Thus, you should return a nice, human-readable string for the object's
The previous :meth:`~Model.__unicode__()` example could be similarly written
using ``__str__()`` like this::
from django.db import models
from django.utils.encoding import force_bytes
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@ -490,6 +499,7 @@ function is usually the best approach.)
For example::
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('people.views.details', args=[str(self.id)])
One place Django uses ``get_absolute_url()`` is in the admin app. If an object

View File

@ -145,6 +145,12 @@ Django quotes column and table names behind the scenes.
and a question has more than one answer, and the order of answers matters, you'd
do this::
from django.db import models
class Question(models.Model):
text = models.TextField()
# ...
class Answer(models.Model):
question = models.ForeignKey(Question)
# ...

View File

@ -232,6 +232,7 @@ the model field that is being aggregated.
For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog::
>>> from django.db.models import Count
>>> q = Blog.objects.annotate(Count('entry'))
# The name of the first blog
>>> q[0].name
@ -699,6 +700,8 @@ And here's ``select_related`` lookup::
``select_related()`` follows foreign keys as far as possible. If you have the
following models::
from django.db import models
class City(models.Model):
# ...
pass
@ -814,6 +817,8 @@ that are supported by ``select_related``. It also supports prefetching of
For example, suppose you have these models::
from django.db import models
class Topping(models.Model):
name = models.CharField(max_length=30)
@ -1565,6 +1570,7 @@ aggregated.
For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries::
>>> from django.db.models import Count
>>> q = Blog.objects.aggregate(Count('entry'))
{'entry__count': 16}
@ -2042,6 +2048,7 @@ Range test (inclusive).
Example::
import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))

View File

@ -12,8 +12,11 @@ Related objects reference
* The "other side" of a :class:`~django.db.models.ForeignKey` relation.
That is::
from django.db import models
class Reporter(models.Model):
...
# ...
pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter)
@ -24,7 +27,8 @@ Related objects reference
* Both sides of a :class:`~django.db.models.ManyToManyField` relation::
class Topping(models.Model):
...
# ...
pass
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)

View File

@ -215,6 +215,7 @@ re-rendered, you can re-evaluate the rendered content, and assign
the content of the response manually::
# Set up a rendered TemplateResponse
>>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {})
>>> t.render()
>>> print(t.content)
@ -256,6 +257,8 @@ To define a post-render callback, just define a function that takes
a single argument -- response -- and register that function with
the template response::
from django.template.response import TemplateResponse
def my_render_callback(response):
# Do content-sensitive processing
do_post_processing()

View File

@ -248,7 +248,7 @@ specify the objects that the view will operate upon -- you can also
specify the list of objects using the ``queryset`` argument::
from django.views.generic import DetailView
from books.models import Publisher, Book
from books.models import Publisher
class PublisherDetail(DetailView):
@ -326,6 +326,7 @@ various useful things are stored on ``self``; as well as the request
Here, we have a URLconf with a single captured group::
# urls.py
from django.conf.urls import patterns
from books.views import PublisherBookList
urlpatterns = patterns('',
@ -375,6 +376,7 @@ Imagine we had a ``last_accessed`` field on our ``Author`` object that we were
using to keep track of the last time anybody looked at that author::
# models.py
from django.db import models
class Author(models.Model):
salutation = models.CharField(max_length=10)
@ -390,6 +392,7 @@ updated.
First, we'd need to add an author detail bit in the URLconf to point to a
custom view::
from django.conf.urls import patterns, url
from books.views import AuthorDetailView
urlpatterns = patterns('',
@ -401,7 +404,6 @@ Then we'd write our new view -- ``get_object`` is the method that retrieves the
object -- so we simply override it and wrap the call::
from django.views.generic import DetailView
from django.shortcuts import get_object_or_404
from django.utils import timezone
from books.models import Author

View File

@ -222,6 +222,7 @@ works for AJAX requests as well as 'normal' form POSTs::
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author
class AjaxableResponseMixin(object):
"""

View File

@ -258,6 +258,7 @@ mixin.
We can hook this into our URLs easily enough::
# urls.py
from django.conf.urls import patterns, url
from books.views import RecordInterest
urlpatterns = patterns('',
@ -440,6 +441,7 @@ Our new ``AuthorDetail`` looks like this::
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic.edit import FormMixin
from books.models import Author
class AuthorInterestForm(forms.Form):
message = forms.CharField()
@ -546,6 +548,8 @@ template as ``AuthorDisplay`` is using on ``GET``.
.. code-block:: python
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
@ -657,6 +661,8 @@ own version of :class:`~django.views.generic.detail.DetailView` by mixing
:class:`~django.views.generic.detail.DetailView` before template
rendering behavior has been mixed in)::
from django.views.generic.detail import BaseDetailView
class JSONDetailView(JSONResponseMixin, BaseDetailView):
pass
@ -675,6 +681,8 @@ and override the implementation of
to defer to the appropriate subclass depending on the type of response that the
user requested::
from django.views.generic.detail import SingleObjectTemplateResponseMixin
class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
def render_to_response(self, context):
# Look for a 'format=json' GET argument

View File

@ -18,6 +18,8 @@ used to track the inventory for a series of online bookstores:
.. code-block:: python
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
@ -123,7 +125,7 @@ If you want to generate more than one aggregate, you just add another
argument to the ``aggregate()`` clause. So, if we also wanted to know
the maximum and minimum price of all books, we would issue the query::
>>> from django.db.models import Avg, Max, Min, Count
>>> from django.db.models import Avg, Max, Min
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
@ -148,6 +150,7 @@ the number of authors:
.. code-block:: python
# Build an annotated queryset
>>> from django.db.models import Count
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
@ -192,6 +195,7 @@ and aggregate the related value.
For example, to find the price range of books offered in each store,
you could use the annotation::
>>> from django.db.models import Max, Min
>>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
This tells Django to retrieve the ``Store`` model, join (through the
@ -222,7 +226,7 @@ For example, we can ask for all publishers, annotated with their respective
total book stock counters (note how we use ``'book'`` to specify the
``Publisher`` -> ``Book`` reverse foreign key hop)::
>>> from django.db.models import Count, Min, Sum, Max, Avg
>>> from django.db.models import Count, Min, Sum, Avg
>>> Publisher.objects.annotate(Count('book'))
(Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
@ -269,6 +273,7 @@ constraining the objects for which an annotation is calculated. For example,
you can generate an annotated list of all books that have a title starting
with "Django" using the query::
>>> from django.db.models import Count, Avg
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
When used with an ``aggregate()`` clause, a filter has the effect of
@ -407,6 +412,8 @@ particularly, when counting things.
By way of example, suppose you have a model like this::
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=10)
data = models.IntegerField()
@ -457,5 +464,6 @@ For example, if you wanted to calculate the average number of authors per
book you first annotate the set of books with the author count, then
aggregate that author count, referencing the annotation field::
>>> from django.db.models import Count, Avg
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
{'num_authors__avg': 1.66}

View File

@ -62,6 +62,8 @@ For example, this custom ``Manager`` offers a method ``with_counts()``, which
returns a list of all ``OpinionPoll`` objects, each with an extra
``num_responses`` attribute that is the result of an aggregate query::
from django.db import models
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
@ -101,6 +103,8 @@ Modifying initial Manager QuerySets
A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
example, using this model::
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
@ -236,7 +240,7 @@ class, but still customize the default manager. For example, suppose you have
this base class::
class AbstractBase(models.Model):
...
# ...
objects = CustomManager()
class Meta:
@ -246,14 +250,15 @@ If you use this directly in a subclass, ``objects`` will be the default
manager if you declare no managers in the base class::
class ChildA(AbstractBase):
...
# ...
# This class has CustomManager as the default manager.
pass
If you want to inherit from ``AbstractBase``, but provide a different default
manager, you can provide the default manager on the child class::
class ChildB(AbstractBase):
...
# ...
# An explicit default manager.
default_manager = OtherManager()
@ -274,9 +279,10 @@ it into the inheritance hierarchy *after* the defaults::
abstract = True
class ChildC(AbstractBase, ExtraManager):
...
# ...
# Default manager is CustomManager, but OtherManager is
# also available via the "extra_manager" attribute.
pass
Note that while you can *define* a custom manager on the abstract model, you
can't *invoke* any methods using the abstract model. That is::
@ -349,8 +355,7 @@ the manager class::
class MyManager(models.Manager):
use_for_related_fields = True
...
# ...
If this attribute is set on the *default* manager for a model (only the
default manager is considered in these situations), Django will use that class
@ -396,7 +401,8 @@ it, whereas the following will not work::
# BAD: Incorrect code
class MyManager(models.Manager):
...
# ...
pass
# Sets the attribute on an instance of MyManager. Django will
# ignore this setting.
@ -404,7 +410,7 @@ it, whereas the following will not work::
mgr.use_for_related_fields = True
class MyModel(models.Model):
...
# ...
objects = mgr
# End of incorrect code.

View File

@ -90,6 +90,8 @@ attributes. Be careful not to choose field names that conflict with the
Example::
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@ -290,8 +292,11 @@ For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
``Manufacturer`` makes multiple cars but each ``Car`` only has one
``Manufacturer`` -- use the following definitions::
from django.db import models
class Manufacturer(models.Model):
# ...
pass
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
@ -340,8 +345,11 @@ For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
-- here's how you'd represent that::
from django.db import models
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
# ...
@ -403,6 +411,8 @@ intermediate model. The intermediate model is associated with the
that will act as an intermediary. For our musician example, the code would look
something like this::
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
@ -583,6 +593,7 @@ It's perfectly OK to relate a model to one from another app. To do this, import
the related model at the top of the file where your model is defined. Then,
just refer to the other model class wherever needed. For example::
from django.db import models
from geography.models import ZipCode
class Restaurant(models.Model):
@ -630,6 +641,8 @@ Meta options
Give your model metadata by using an inner ``class Meta``, like so::
from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
@ -660,6 +673,8 @@ model.
For example, this model has a few custom methods::
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@ -729,6 +744,8 @@ A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example (see
:meth:`~Model.save` for documentation of the parameters it accepts)::
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
@ -740,6 +757,8 @@ to happen whenever you save an object. For example (see
You can also prevent saving::
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
@ -826,6 +845,8 @@ the child (and Django will raise an exception).
An example::
from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
@ -854,14 +875,16 @@ attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
from django.db import models
class CommonInfo(models.Model):
...
# ...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
...
# ...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
@ -901,6 +924,8 @@ abstract base class (only), part of the name should contain
For example, given an app ``common/models.py``::
from django.db import models
class Base(models.Model):
m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
@ -949,6 +974,8 @@ relationship introduces links between the child model and each of its parents
(via an automatically-created :class:`~django.db.models.OneToOneField`).
For example::
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
@ -998,7 +1025,7 @@ If the parent has an ordering and you don't want the child to have any natural
ordering, you can explicitly disable it::
class ChildModel(ParentModel):
...
# ...
class Meta:
# Remove parent's ordering effect
ordering = []
@ -1061,15 +1088,21 @@ Proxy models are declared like normal models. You tell Django that it's a
proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
the ``Meta`` class to ``True``.
For example, suppose you want to add a method to the ``Person`` model described
above. You can do it like this::
For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class MyPerson(Person):
class Meta:
proxy = True
def do_something(self):
...
# ...
pass
The ``MyPerson`` class operates on the same database table as its parent
``Person`` class. In particular, any new instances of ``Person`` will also be
@ -1125,8 +1158,11 @@ classes will still be available.
Continuing our example from above, you could change the default manager used
when you query the ``Person`` model like this::
from django.db import models
class NewManager(models.Manager):
...
# ...
pass
class MyPerson(Person):
objects = NewManager()

View File

@ -17,6 +17,8 @@ models, which comprise a Weblog application:
.. code-block:: python
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

View File

@ -27,6 +27,8 @@ to deal with that file.
Consider the following model, using an :class:`~django.db.models.ImageField` to
store a photo::
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)

View File

@ -15,6 +15,7 @@ Basic file uploads
Consider a simple form containing a :class:`~django.forms.FileField`::
# In forms.py...
from django import forms
class UploadFileForm(forms.Form):
@ -39,6 +40,7 @@ something like::
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from .forms import UploadFileForm
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

View File

@ -123,6 +123,8 @@ is ``(?P<name>pattern)``, where ``name`` is the name of the group and
Here's the above example URLconf, rewritten to use named groups::
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^articles/2003/$', 'news.views.special_case_2003'),
url(r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
@ -192,6 +194,8 @@ A convenient trick is to specify default parameters for your views' arguments.
Here's an example URLconf and view::
# URLconf
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^blog/$', 'blog.views.page'),
url(r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
@ -370,11 +374,15 @@ An included URLconf receives any captured parameters from parent URLconfs, so
the following example is valid::
# In settings/urls/main.py
from django.conf.urls import include, patterns, url
urlpatterns = patterns('',
url(r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
)
# In foo/urls/blog.py
from django.conf.urls import patterns, url
urlpatterns = patterns('foo.views',
url(r'^$', 'blog.index'),
url(r'^archive/$', 'blog.archive'),
@ -397,6 +405,8 @@ function.
For example::
from django.conf.urls import patterns, url
urlpatterns = patterns('blog.views',
url(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)
@ -427,11 +437,15 @@ For example, these two URLconf sets are functionally identical:
Set one::
# main.py
from django.conf.urls import include, patterns, url
urlpatterns = patterns('',
url(r'^blog/', include('inner'), {'blogid': 3}),
)
# inner.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^archive/$', 'mysite.views.archive'),
url(r'^about/$', 'mysite.views.about'),
@ -440,11 +454,15 @@ Set one::
Set two::
# main.py
from django.conf.urls import include, patterns, url
urlpatterns = patterns('',
url(r'^blog/', include('inner')),
)
# inner.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
url(r'^about/$', 'mysite.views.about', {'blogid': 3}),
@ -464,6 +482,8 @@ supported -- you can pass any callable object as the view.
For example, given this URLconf in "string" notation::
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^archive/$', 'mysite.views.archive'),
url(r'^about/$', 'mysite.views.about'),
@ -473,6 +493,7 @@ For example, given this URLconf in "string" notation::
You can accomplish the same thing by passing objects rather than strings. Just
be sure to import the objects::
from django.conf.urls import patterns, url
from mysite.views import archive, about, contact
urlpatterns = patterns('',
@ -485,6 +506,7 @@ The following example is functionally identical. It's just a bit more compact
because it imports the module that contains the views, rather than importing
each view individually::
from django.conf.urls import patterns, url
from mysite import views
urlpatterns = patterns('',
@ -501,6 +523,7 @@ the view prefix (as explained in "The view prefix" above) will have no effect.
Note that :doc:`class based views</topics/class-based-views/index>` must be
imported::
from django.conf.urls import patterns, url
from mysite.views import ClassBasedView
urlpatterns = patterns('',
@ -612,6 +635,9 @@ It's fairly common to use the same view function in multiple URL patterns in
your URLconf. For example, these two URL patterns both point to the ``archive``
view::
from django.conf.urls import patterns, url
from mysite.views import archive
urlpatterns = patterns('',
url(r'^archive/(\d{4})/$', archive),
url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}),
@ -630,6 +656,9 @@ matching.
Here's the above example, rewritten to use named URL patterns::
from django.conf.urls import patterns, url
from mysite.views import archive
urlpatterns = patterns('',
url(r'^archive/(\d{4})/$', archive, name="full-archive"),
url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, name="arch-summary"),
@ -803,6 +832,8 @@ However, you can also ``include()`` a 3-tuple containing::
For example::
from django.conf.urls import include, patterns, url
help_patterns = patterns('',
url(r'^basic/$', 'apps.help.views.views.basic'),
url(r'^advanced/$', 'apps.help.views.views.advanced'),

View File

@ -70,6 +70,8 @@ documentation. Just return an instance of one of those subclasses instead of
a normal :class:`~django.http.HttpResponse` in order to signify an error. For
example::
from django.http import HttpResponse, HttpResponseNotFound
def my_view(request):
# ...
if foo:
@ -83,6 +85,8 @@ the :class:`~django.http.HttpResponse` documentation, you can also pass the
HTTP status code into the constructor for :class:`~django.http.HttpResponse`
to create a return class for any status code you like. For example::
from django.http import HttpResponse
def my_view(request):
# ...
@ -110,6 +114,8 @@ standard error page for your application, along with an HTTP error code 404.
Example usage::
from django.http import Http404
from django.shortcuts import render_to_response
from polls.models import Poll
def detail(request, poll_id):
try: