Django documentation

  • 1.0
  • 1.1
  • 1.2
  • 1.3
  • 1.4
  • 1.5
  • Documentation version: dev

URL dispatcher¶

A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs however you want, with no framework limitations.

There’s no .php or .cgi required, and certainly none of that 0,2097,1-1-1928,00 nonsense.

See Cool URIs don’t change, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable.

Overview¶

To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a simple mapping between URL patterns (simple regular expressions) to Python functions (your views).

This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.

New in Django 1.4: Django also provides a way to translate URLs according to the active language. See the internationalization documentation for more information.

How Django processes a request¶

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.
  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.patterns().
  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
  4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function (or a class based view). The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
  5. If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.

Example¶

Here’s a sample URLconf:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^articles/2003/$', 'news.views.special_case_2003'),
    (r'^articles/(\d{4})/$', 'news.views.year_archive'),
    (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)

Notes:

  • To capture a value from the URL, just put parenthesis around it.
  • There's no need to add a leading slash, because every URL has that. For example, it's ^articles, not ^/articles.
  • The 'r' in front of each regular expression string is optional but recommended. It tells Python that a string is "raw" -- that nothing in the string should be escaped. See Dive Into Python's explanation.

Example requests:

  • A request to /articles/2005/03/ would match the third entry in the list. Django would call the function news.views.month_archive(request, '2005', '03').
  • /articles/2005/3/ would not match any URL patterns, because the third entry in the list requires two digits for the month.
  • /articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this.
  • /articles/2003 would not match any of these patterns, because each pattern requires that the URL end with a slash.
  • /articles/2003/03/03/ would match the final pattern. Django would call the function news.views.article_detail(request, '2003', '03', '03').

Named groups¶

The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it's possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern), where name is the name of the group and pattern is some pattern to match.

Here's the above example URLconf, rewritten to use named groups:

urlpatterns = patterns('',
    (r'^articles/2003/$', 'news.views.special_case_2003'),
    (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
    (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
    (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', 'news.views.article_detail'),
)

This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments. For example:

  • A request to /articles/2005/03/ would call the function news.views.month_archive(request, year='2005', month='03'), instead of news.views.month_archive(request, '2005', '03').
  • A request to /articles/2003/03/03/ would call the function news.views.article_detail(request, year='2003', month='03', day='03').

In practice, this means your URLconfs are slightly more explicit and less prone to argument-order bugs -- and you can reorder the arguments in your views' function definitions. Of course, these benefits come at the cost of brevity; some developers find the named-group syntax ugly and too verbose.

The matching/grouping algorithm¶

Here's the algorithm the URLconf parser follows, with respect to named groups vs. non-named groups in a regular expression:

  1. If there are any named arguments, it will use those, ignoring non-named arguments.
  2. Otherwise, it will pass all non-named arguments as positional arguments.

In both cases, any extra keyword arguments that have been given as per Passing extra options to view functions (below) will also be passed to the view.

What the URLconf searches against¶

The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.

For example, in a request to www.example.com/myapp/, the URLconf will look for myapp/.

In a request to www.example.com/myapp/?page=3, the URLconf will look for myapp/.

The URLconf doesn't look at the request method. In other words, all request methods -- POST, GET, HEAD, etc. -- will be routed to the same function for the same URL.

Notes on capturing text in URLs¶

Each captured argument is sent to the view as a plain Python string, regardless of what sort of match the regular expression makes. For example, in this URLconf line:

(r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),

...the year argument to news.views.year_archive() will be a string, not an integer, even though the \d{4} will only match integer strings.

A convenient trick is to specify default parameters for your views' arguments. Here's an example URLconf and view:

# URLconf
urlpatterns = patterns('',
    (r'^blog/$', 'blog.views.page'),
    (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
)

# View (in blog/views.py)
def page(request, num="1"):
    # Output the appropriate page of blog entries, according to num.

In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex.

Performance¶

Each regular expression in a urlpatterns is compiled the first time it's accessed. This makes the system blazingly fast.

Syntax of the urlpatterns variable¶

urlpatterns should be a Python list, in the format returned by the function django.conf.urls.patterns(). Always use patterns() to create the urlpatterns variable.

Error handling¶

When Django can't find a regex matching the requested URL, or when an exception is raised, Django will invoke an error-handling view.

The views to use for these cases are specified by three variables. Their default values should suffice for most projects, but further customization is possible by assigning values to them.

See the documentation on customizing error views for the full details.

Such values can be set in your root URLconf. Setting these variables in any other URLconf will have no effect.

Values must be callables, or strings representing the full Python import path to the view that should be called to handle the error condition at hand.

The variables are:

  • handler404 -- See django.conf.urls.handler404.
  • handler500 -- See django.conf.urls.handler500.
  • handler403 -- See django.conf.urls.handler403.
New in Django 1.4: handler403 is new in Django 1.4.

The view prefix¶

You can specify a common prefix in your patterns() call, to cut down on code duplication.

Here's the example URLconf from the Django overview:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^articles/(\d{4})/$', 'news.views.year_archive'),
    (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)

In this example, each view has a common prefix -- 'news.views'. Instead of typing that out for each entry in urlpatterns, you can use the first argument to the patterns() function to specify a prefix to apply to each view function.

With this in mind, the above example can be written more concisely as:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'),
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'),
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'),
)

Note that you don't put a trailing dot (".") in the prefix. Django puts that in automatically.

Multiple view prefixes¶

In practice, you'll probably end up mixing and matching views to the point where the views in your urlpatterns won't have a common prefix. However, you can still take advantage of the view prefix shortcut to remove duplication. Just add multiple patterns() objects together, like this:

Old:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^$', 'myapp.views.app_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'myapp.views.month_display'),
    (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
)

New:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('myapp.views',
    (r'^$', 'app_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','month_display'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)

Including other URLconfs¶

At any point, your urlpatterns can "include" other URLconf modules. This essentially "roots" a set of URLs below other ones.

For example, here's an excerpt of the URLconf for the Django Web site itself. It includes a number of other URLconfs:

from django.conf.urls import patterns, include

urlpatterns = patterns('',
    # ... snip ...
    (r'^comments/', include('django.contrib.comments.urls')),
    (r'^community/', include('django_website.aggregator.urls')),
    (r'^contact/', include('django_website.contact.urls')),
    (r'^r/', include('django.conf.urls.shortcut')),
    # ... snip ...
)

Note that the regular expressions in this example don't have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.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.

Another possibility is to include additional URL patterns not by specifying the URLconf Python module defining them as the include() argument but by using directly the pattern list as returned by patterns() instead. For example, consider this URLconf:

from django.conf.urls import patterns, url, include

extra_patterns = patterns('',
    url(r'^reports/(?P<id>\d+)/$', 'credit.views.report'),
    url(r'^charge/$', 'credit.views.charge'),
)

urlpatterns = patterns('',
    url(r'^$', 'apps.main.views.homepage'),
    (r'^help/', include('apps.help.urls')),
    (r'^credit/', include(extra_patterns)),
)

In this example, the /credit/reports/ URL will be handled by the credit.views.report() Django view.

Captured parameters¶

An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid:

# In settings/urls/main.py
urlpatterns = patterns('',
    (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
)

# In foo/urls/blog.py
urlpatterns = patterns('foo.views',
    (r'^$', 'blog.index'),
    (r'^archive/$', 'blog.archive'),
)

In the above example, the captured "username" variable is passed to the included URLconf, as expected.

Passing extra options to view functions¶

URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.

Any URLconf tuple can have an optional third element, which should be a dictionary of extra keyword arguments to pass to the view function.

For example:

urlpatterns = patterns('blog.views',
    (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)

In this example, for a request to /blog/2005/, Django will call blog.views.year_archive(year='2005', foo='bar').

This technique is used in the syndication framework to pass metadata and options to views.

Dealing with conflicts

It's possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.

Passing extra options to include()

Similarly, you can pass extra options to include(). When you pass extra options to include(), each line in the included URLconf will be passed the extra options.

For example, these two URLconf sets are functionally identical:

Set one:

# main.py
urlpatterns = patterns('',
    (r'^blog/', include('inner'), {'blogid': 3}),
)

# inner.py
urlpatterns = patterns('',
    (r'^archive/$', 'mysite.views.archive'),
    (r'^about/$', 'mysite.views.about'),
)

Set two:

# main.py
urlpatterns = patterns('',
    (r'^blog/', include('inner')),
)

# inner.py
urlpatterns = patterns('',
    (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
    (r'^about/$', 'mysite.views.about', {'blogid': 3}),
)

Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line's view actually accepts those options as valid. For this reason, this technique is only useful if you're certain that every view in the included URLconf accepts the extra options you're passing.

Passing callable objects instead of strings¶

Some developers find it more natural to pass the actual Python function object rather than a string containing the path to its module. This alternative is supported -- you can pass any callable object as the view.

For example, given this URLconf in "string" notation:

urlpatterns = patterns('',
    (r'^archive/$', 'mysite.views.archive'),
    (r'^about/$', 'mysite.views.about'),
    (r'^contact/$', 'mysite.views.contact'),
)

You can accomplish the same thing by passing objects rather than strings. Just be sure to import the objects:

from mysite.views import archive, about, contact

urlpatterns = patterns('',
    (r'^archive/$', archive),
    (r'^about/$', about),
    (r'^contact/$', contact),
)

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 mysite import views

urlpatterns = patterns('',
    (r'^archive/$', views.archive),
    (r'^about/$', views.about),
    (r'^contact/$', views.contact),
)

The style you use is up to you.

Note that if you use this technique -- passing objects rather than strings -- the view prefix (as explained in "The view prefix" above) will have no effect.

Note that class based views must be imported:

from mysite.views import ClassBasedView

urlpatterns = patterns('',
    (r'^myview/$', ClassBasedView.as_view()),
)

Reverse resolution of URLs¶

A common need when working on a Django project is the possibility to obtain URLs in their final forms either for embedding in generated content (views and assets URLs, URLs shown to the user, etc.) or for handling of the navigation flow on the server side (redirections, etc.)

It is strongly desirable not having to hard-code these URLs (a laborious, non-scalable and error-prone strategy) or having to devise ad-hoc mechanisms for generating URLs that are parallel to the design described by the URLconf and as such in danger of producing stale URLs at some point.

In other words, what's needed is a DRY mechanism. Among other advantages it would allow evolution of the URL design without having to go all over the project source code to search and replace outdated URLs.

The piece of information we have available as a starting point to get a URL is an identification (e.g. the name) of the view in charge of handling it, other pieces of information that necessarily must participate in the lookup of the right URL are the types (positional, keyword) and values of the view arguments.

Django provides a solution such that the URL mapper is the only repository of the URL design. You feed it with your URLconf and then it can be used in both directions:

  • Starting with a URL requested by the user/browser, it calls the right Django view providing any arguments it might need with their values as extracted from the URL.
  • Starting with the identification of the corresponding Django view plus the values of arguments that would be passed to it, obtain the associated URL.

The first one is the usage we've been discussing in the previous sections. The second one is what is known as reverse resolution of URLs, reverse URL matching, reverse URL lookup, or simply URL reversing.

Django provides tools for performing URL reversing that match the different layers where URLs are needed:

  • In templates: Using the url template tag.
  • In Python code: Using the django.core.urlresolvers.reverse() function.
  • In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.

Examples¶

Consider again this URLconf entry:

from django.conf.urls 


gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.