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.

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:

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.

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().

Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL.

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 the following
arguments:

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
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 views.article_detail(request,'2003','03','03').

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.

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
views.month_archive(request,year='2005',month='03'), instead
of views.month_archive(request,'2005','03').

A request to /articles/2003/03/03/ would call the function
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.

In the above example, both URL patterns point to the same view –
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.

It is possible to pass a string containing the path to a view rather than the
actual Python function object. This alternative is supported for the time
being, though is not recommended and will be removed in a future version of
Django.

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.

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:

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:

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

# In settings/urls/main.pyfromdjango.conf.urlsimportinclude,patterns,urlurlpatterns=patterns('',url(r'^(?P<username>\w+)/blog/',include('foo.urls.blog')),)# In foo/urls/blog.pyfromdjango.conf.urlsimportpatterns,urlurlpatterns=patterns('foo.views',url(r'^$','blog.index'),url(r'^archive/$','blog.archive'),)

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

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.

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.

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:

According to this design, the URL for the archive corresponding to year nnnn
is /articles/nnnn/.

You can obtain these in template code by using:

<ahref="{%url'news.views.year_archive'2012%}">2012 Archive</a>{# Or with the year in a template context variable: #}<ul>{%foryearvarinyear_list%}<li><ahref="{%url'news.views.year_archive'yearvar%}">{{yearvar}} Archive</a></li>{%endfor%}</ul>

If, for some reason, it was decided that the URLs where content for yearly
article archives are published at should be changed then you would only need to
change the entry in the URLconf.

In some scenarios where views are of a generic nature, a many-to-one
relationship might exist between URLs and views. For these cases the view name
isn’t a good enough identifier for it when comes the time of reversing
URLs. Read the next section to know about the solution Django provides for this.

This is completely valid, but it leads to problems when you try to do reverse
URL matching (through the reverse() function
or the url template tag). Continuing this example, if you wanted to
retrieve the URL for the archive view, Django’s reverse URL matcher would
get confused, because two URL patterns point at that view.

To solve this problem, Django supports named URL patterns. That is, you can
give a name to a URL pattern in order to distinguish it from other patterns
using the same view and parameters. Then, you can use this name in reverse URL
matching.

With these names in place (full-archive and arch-summary), you can
target each pattern individually by using its name:

{%url'arch-summary'1945%}{%url'full-archive'2007%}

Even though both URL patterns refer to the archive view here, using the
name parameter to django.conf.urls.url() allows you to tell them
apart in templates.

The string used for the URL name can contain any characters you like. You are
not restricted to valid Python names.

Note

When you name your URL patterns, make sure you use names that are unlikely
to clash with any other application’s choice of names. If you call your URL
pattern comment, and another application does the same thing, there’s
no guarantee which URL will be inserted into your template when you use
this name.

Putting a prefix on your URL names, perhaps derived from the application
name, will decrease the chances of collision. We recommend something like
myapp-comment instead of comment.

URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names.
It’s a good practice for third-party apps to always use namespaced URLs (as we
did in the tutorial). Similarly, it also allows you to reverse URLs if multiple
instances of an application are deployed. In other words, since multiple
instances of a single application will share named URLs, namespaces provide a
way to tell these named URLs apart.

Django applications that make proper use of URL namespacing can be deployed more
than once for a particular site. For example django.contrib.admin has an
AdminSite class which allows you to easily
deploy more than once instance of the admin.
In a later example, we’ll discuss the idea of deploying the polls application
from the tutorial in two different locations so we can serve the same
functionality to two different audiences (authors and publishers).

A URL namespace comes in two parts, both of which are strings:

application namespace

This describes the name of the application that is being deployed. Every
instance of a single application will have the same application namespace.
For example, Django’s admin application has the somewhat predictable
application namespace of 'admin'.

instance namespace

This identifies a specific instance of an application. Instance namespaces
should be unique across your entire project. However, an instance namespace
can be the same as the application namespace. This is used to specify a
default instance of an application. For example, the default Django admin
instance has an instance namespace of 'admin'.

Namespaced URLs are specified using the ':' operator. For example, the main
index page of the admin application is referenced using 'admin:index'. This
indicates a namespace of 'admin', and a named URL of 'index'.

Namespaces can also be nested. The named URL 'sports:polls:index' would
look for a pattern named 'index' in the namespace 'polls' that is itself
defined within the top-level namespace 'sports'.

When given a namespaced URL (e.g. 'polls:index') to resolve, Django splits
the fully qualified name into parts and then tries the following lookup:

First, Django looks for a matching application namespace (in this
example, 'polls'). This will yield a list of instances of that
application.

If there is a current application defined, Django finds and returns
the URL resolver for that instance. The current application can be
specified as an attribute on the template context - applications that
expect to have multiple deployments should set the current_app
attribute on any Context or
RequestContext that is used to render a template.

The current application can also be specified manually as an argument
to the reverse() function.

If there is no current application. Django looks for a default
application instance. The default application instance is the instance
that has an instance namespace matching the application
namespace (in this example, an instance of polls called 'polls').

If there is no default application instance, Django will pick the last
deployed instance of the application, whatever its instance name may be.

If there are nested namespaces, these steps are repeated for each part of the
namespace until only the view name is unresolved. The view name will then be
resolved into a URL in the namespace that has been found.

To show this resolution strategy in action, consider an example of two instances
of the polls application from the tutorial: one called 'author-polls'
and one called 'publisher-polls'. Assume we have enhanced that application
so that it takes the instance namespace into consideration when creating and
displaying polls.

If one of the instances is current - say, if we were rendering the detail page
in the instance 'author-polls' - 'polls:index' will resolve to the
index page of the 'author-polls' instance; i.e. both of the following will
result in "/author-polls/".

If there is no current instance - say, if we were rendering a page
somewhere else on the site - 'polls:index' will resolve to the last
registered instance of polls. Since there is no default instance
(instance namespace of 'polls'), the last instance of polls that is
registered will be used. This would be 'publisher-polls' since it’s
declared last in the urlpatterns.

'author-polls:index' will always resolve to the index page of the instance
'author-polls' (and likewise for 'publisher-polls') .

If there were also a default instance - i.e., an instance named 'polls' -
the only change from above would be in the case where there is no current
instance (the second item in the list above). In this case 'polls:index'
would resolve to the index page of the default instance instead of the instance
declared last in urlpatterns.

Secondly, you can include an object that contains embedded namespace data. If
you include() a list of url() instances,
the URLs contained in that object will be added to the global namespace.
However, you can also include() a 3-tuple containing:

This will include the nominated URL patterns into the given application and
instance namespace.

For example, the Django admin is deployed as instances of
AdminSite. AdminSite objects have a urls
attribute: A 3-tuple that contains all the patterns in the corresponding admin
site, plus the application namespace 'admin', and the name of the admin
instance. It is this urls attribute that you include() into your
projects urlpatterns when you deploy an admin instance.

Be sure to pass a tuple to include(). If you simply pass three arguments:
include(polls_patterns,'polls','author-polls'), Django won’t throw an
error but due to the signature of include(), 'polls' will be the
instance namespace and 'author-polls' will be the application namespace
instead of vice versa.