URL dispatcher¶
A clean, elegant URL scheme is an important detail in a high-quality Webapplication. Django lets you design URLs however you want, with no frameworklimitations.
There’s no.php or.cgi required, and certainly none of that0,2097,1-1-1928,00 nonsense.
SeeCool URIs don’t change, by World Wide Web creator Tim Berners-Lee, forexcellent arguments on why URLs should be clean and usable.
Overview¶
To design URLs for an app, you create a Python module informally called aURLconf (URL configuration). This module is pure Python code and is asimple mapping between URL patterns (simple regular expressions) to Pythonfunctions (your views).
This mapping can be as short or as long as needed. It can reference othermappings. And, because it’s pure Python code, it can be constructeddynamically.
Django also provides a way to translate URLs according to the activelanguage. See theinternationalization documentation for more information.
How Django processes a request¶
When a user requests a page from your Django-powered site, this is thealgorithm 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_URLCONFsetting, but if the incomingHttpRequestobject has aurlconfattribute (set by middleware), its value will be used in place of theROOT_URLCONFsetting. - Django loads that Python module and looks for the variable
urlpatterns. This should be a Python list ofdjango.conf.urls.url()instances. - Django runs through each URL pattern, in order, and stops at the firstone 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 aclass-based view). The view gets passed the followingarguments:
- An instance of
HttpRequest. - If the matched regular expression returned no named groups, then thematches from the regular expression are provided as positional arguments.
- The keyword arguments are made up of any named groups matched by theregular expression, overridden by any arguments specified in the optional
kwargsargument todjango.conf.urls.url().
- An instance of
- If no regex matches, or if an exception is raised during anypoint in this process, Django invokes an appropriateerror-handling view. SeeError handling below.
Example¶
Here’s a sample URLconf:
fromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^articles/2003/$',views.special_case_2003),url(r'^articles/([0-9]{4})/$',views.year_archive),url(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',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. Forexample, it’s
^articles, not^/articles. - The
'r'in front of each regular expression string is optional butrecommended. It tells Python that a string is “raw” – that nothing inthe string should be escaped. SeeDive Into Python’s explanation.
Example requests:
- A request to
/articles/2005/03/would match the third entry in thelist. Django would call the functionviews.month_archive(request,'2005','03'). /articles/2005/3/would not match any URL patterns, because thethird entry in the list requires two digits for the month./articles/2003/would match the first pattern in the list, not thesecond one, because the patterns are tested in order, and the first oneis the first test to pass. Feel free to exploit the ordering to insertspecial cases like this. Here, Django would call the functionviews.special_case_2003(request)/articles/2003would not match any of these patterns, because eachpattern requires that the URL end with a slash./articles/2003/03/03/would match the final pattern. Django would callthe functionviews.article_detail(request,'2003','03','03').
Named groups¶
The above example used simple,non-named regular-expression groups (viaparenthesis) to capture bits of the URL and pass them aspositional argumentsto a view. In more advanced usage, it’s possible to usenamedregular-expression groups to capture URL bits and pass them askeywordarguments to a view.
In Python regular expressions, the syntax for named regular-expression groupsis(?P<name>pattern), wherename is the name of the group andpattern is some pattern to match.
Here’s the above example URLconf, rewritten to use named groups:
fromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^articles/2003/$',views.special_case_2003),url(r'^articles/(?P<year>[0-9]{4})/$',views.year_archive),url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',views.month_archive),url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$',views.article_detail),]
This accomplishes exactly the same thing as the previous example, with onesubtle difference: The captured values are passed to view functions as keywordarguments rather than positional arguments. For example:
- A request to
/articles/2005/03/would call the functionviews.month_archive(request,year='2005',month='03'), insteadofviews.month_archive(request,'2005','03'). - A request to
/articles/2003/03/03/would call the functionviews.article_detail(request,year='2003',month='03',day='03').
In practice, this means your URLconfs are slightly more explicit and less proneto 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 groupsvs. non-named groups in a regular expression:
- If there are any named arguments, it will use those, ignoring non-namedarguments.
- Otherwise, it will pass all non-named arguments as positional arguments.
In both cases, any extra keyword arguments that have been given as perPassingextra 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. Thisdoes not include GET or POST parameters, or the domain name.
For example, in a request tohttps://www.example.com/myapp/, the URLconfwill look formyapp/.
In a request tohttps://www.example.com/myapp/?page=3, the URLconf will lookformyapp/.
The URLconf doesn’t look at the request method. In other words, all requestmethods –POST,GET,HEAD, etc. – will be routed to the samefunction for the same URL.
Captured arguments are always strings¶
Each captured argument is sent to the view as a plain Python string, regardlessof what sort of match the regular expression makes. For example, in thisURLconf line:
url(r'^articles/(?P<year>[0-9]{4})/$',views.year_archive),
- …the
yearargument passed toviews.year_archive()will be a string, - not an integer, even though the
[0-9]{4}will only match integer strings.
Specifying defaults for view arguments¶
A convenient trick is to specify default parameters for your views’ arguments.Here’s an example URLconf and view:
# URLconffromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^blog/$',views.page),url(r'^blog/page(?P<num>[0-9]+)/$',views.page),]# View (in blog/views.py)defpage(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 –views.page – but the first pattern doesn’t capture anything from theURL. If the first pattern matches, thepage() function will use itsdefault argument fornum,"1". If the second pattern matches,page() will use whatevernum value was captured by the regex.
Performance¶
Each regular expression in aurlpatterns is compiled the first time it’saccessed. This makes the system blazingly fast.
Error handling¶
When Django can’t find a regex matching the requested URL, or when anexception is raised, Django will invoke an error-handling view.
The views to use for these cases are specified by four variables. Theirdefault values should suffice for most projects, but further customization ispossible by overriding their default values.
See the documentation oncustomizing error views for the full details.
Such values can be set in your root URLconf. Setting these variables in anyother URLconf will have no effect.
Values must be callables, or strings representing the full Python import pathto the view that should be called to handle the error condition at hand.
The variables are:
handler400– Seedjango.conf.urls.handler400.handler403– Seedjango.conf.urls.handler403.handler404– Seedjango.conf.urls.handler404.handler500– Seedjango.conf.urls.handler500.
Including other URLconfs¶
At any point, yoururlpatterns can “include” other URLconf modules. Thisessentially “roots” a set of URLs below other ones.
For example, here’s an excerpt of the URLconf for theDjango websiteitself. It includes a number of other URLconfs:
fromdjango.conf.urlsimportinclude,urlurlpatterns=[# ... snip ...url(r'^community/',include('django_website.aggregator.urls')),url(r'^contact/',include('django_website.contact.urls')),# ... snip ...]
Note that the regular expressions in this example don’t have a$(end-of-string match character) but do include a trailing slash. WheneverDjango encountersinclude() (django.conf.urls.include()), it chopsoff whatever part of the URL matched up to that point and sends the remainingstring to the included URLconf for further processing.
Another possibility is to include additional URL patterns by using a list ofurl() instances. For example, consider this URLconf:
fromdjango.conf.urlsimportinclude,urlfromapps.mainimportviewsasmain_viewsfromcreditimportviewsascredit_viewsextra_patterns=[url(r'^reports/$',credit_views.report),url(r'^reports/(?P<id>[0-9]+)/$',credit_views.report),url(r'^charge/$',credit_views.charge),]urlpatterns=[url(r'^$',main_views.homepage),url(r'^help/',include('apps.help.urls')),url(r'^credit/',include(extra_patterns)),]
In this example, the/credit/reports/ URL will be handled by thecredit_views.report() Django view.
This can be used to remove redundancy from URLconfs where a single patternprefix is used repeatedly. For example, consider this URLconf:
fromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/history/$',views.history),url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/edit/$',views.edit),url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/discuss/$',views.discuss),url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/permissions/$',views.permissions),]
We can improve this by stating the common path prefix only once and groupingthe suffixes that differ:
fromdjango.conf.urlsimportinclude,urlfrom.importviewsurlpatterns=[url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/',include([url(r'^history/$',views.history),url(r'^edit/$',views.edit),url(r'^discuss/$',views.discuss),url(r'^permissions/$',views.permissions),])),]
Captured parameters¶
An included URLconf receives any captured parameters from parent URLconfs, sothe following example is valid:
# In settings/urls/main.pyfromdjango.conf.urlsimportinclude,urlurlpatterns=[url(r'^(?P<username>\w+)/blog/',include('foo.urls.blog')),]# In foo/urls/blog.pyfromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^$',views.blog.index),url(r'^archive/$',views.blog.archive),]
In the above example, the captured"username" variable is passed to theincluded URLconf, as expected.
Nested arguments¶
Regular expressions allow nested arguments, and Django will resolve them andpass them to the view. When reversing, Django will try to fill in all outercaptured arguments, ignoring any nested captured arguments. Consider thefollowing URL patterns which optionally take a page argument:
fromdjango.conf.urlsimporturlurlpatterns=[url(r'blog/(page-(\d+)/)?$',blog_articles),# badurl(r'comments/(?:page-(?P<page_number>\d+)/)?$',comments),# good]
Both patterns use nested arguments and will resolve: for example,blog/page-2/ will result in a match toblog_articles with twopositional arguments:page-2/ and2. The second pattern forcomments will matchcomments/page-2/ with keyword argumentpage_number set to 2. The outer argument in this case is a non-capturingargument(?:...).
Theblog_articles view needs the outermost captured argument to be reversed,page-2/ or no arguments in this case, whilecomments can be reversedwith either no arguments or a value forpage_number.
Nested captured arguments create a strong coupling between the view argumentsand the URL as illustrated byblog_articles: the view receives part of theURL (page-2/) instead of only the value the view is interested in. Thiscoupling is even more pronounced when reversing, since to reverse the view weneed to pass the piece of URL instead of the page number.
As a rule of thumb, only capture the values the view needs to work with anduse non-capturing arguments when the regular expression needs an argument butthe view ignores it.
Passing extra options to view functions¶
URLconfs have a hook that lets you pass extra arguments to your view functions,as a Python dictionary.
Thedjango.conf.urls.url() function can take an optional third argumentwhich should be a dictionary of extra keyword arguments to pass to the viewfunction.
For example:
fromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[url(r'^blog/(?P<year>[0-9]{4})/$',views.year_archive,{'foo':'bar'}),]
In this example, for a request to/blog/2005/, Django will callviews.year_archive(request,year='2005',foo='bar').
This technique is used in thesyndication framework to pass metadata andoptions 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 extraarguments. When this happens, the arguments in the dictionary will be usedinstead of the arguments captured in the URL.
Passing extra options toinclude()¶
Similarly, you can pass extra options toinclude().When you pass extra options toinclude(),each line in the includedURLconf will be passed the extra options.
For example, these two URLconf sets are functionally identical:
Set one:
# main.pyfromdjango.conf.urlsimportinclude,urlurlpatterns=[url(r'^blog/',include('inner'),{'blogid':3}),]# inner.pyfromdjango.conf.urlsimporturlfrommysiteimportviewsurlpatterns=[url(r'^archive/$',views.archive),url(r'^about/$',views.about),]
Set two:
# main.pyfromdjango.conf.urlsimportinclude,urlfrommysiteimportviewsurlpatterns=[url(r'^blog/',include('inner')),]# inner.pyfromdjango.conf.urlsimporturlurlpatterns=[url(r'^archive/$',views.archive,{'blogid':3}),url(r'^about/$',views.about,{'blogid':3}),]
Note that extra options willalways be passed toevery line in the includedURLconf, regardless of whether the line’s view actually accepts those optionsas valid. For this reason, this technique is only useful if you’re certain thatevery view in the included URLconf accepts the extra options you’re passing.
Reverse resolution of URLs¶
A common need when working on a Django project is the possibility to obtain URLsin their final forms either for embedding in generated content (views and assetsURLs, URLs shown to the user, etc.) or for handling of the navigation flow onthe server side (redirections, etc.)
It is strongly desirable to avoid hard-coding these URLs (a laborious,non-scalable and error-prone strategy). Equally dangerous is devising ad-hocmechanisms to generate URLs that are parallel to the design described by theURLconf, which can result in the production of URLs that become stale over time.
In other words, what’s needed is a DRY mechanism. Among other advantages itwould allow evolution of the URL design without having to go over all theproject source code to search and replace outdated URLs.
The primary piece of information we have available to get a URL is anidentification (e.g. the name) of the view in charge of handling it. Otherpieces of information that necessarily must participate in the lookup of theright 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 ofthe URL design. You feed it with your URLconf and then it can be used in bothdirections:
- Starting with a URL requested by the user/browser, it calls the right Djangoview providing any arguments it might need with their values as extracted fromthe URL.
- Starting with the identification of the corresponding Django view plus thevalues 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. Thesecond one is what is known asreverse resolution of URLs,reverse URLmatching,reverse URL lookup, or simplyURL reversing.
Django provides tools for performing URL reversing that match the differentlayers where URLs are needed:
- In templates: Using the
urltemplate tag. - In Python code: Using the
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:
fromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[#...url(r'^articles/([0-9]{4})/$',views.year_archive,name='news-year-archive'),#...]
According to this design, the URL for the archive corresponding to yearnnnnis/articles/nnnn/.
You can obtain these in template code by using:
<ahref="{%url'news-year-archive'2012%}">2012 Archive</a>{# Or with the year in a template context variable: #}<ul>{%foryearvarinyear_list%}<li><ahref="{%url'news-year-archive'yearvar%}">{{yearvar}} Archive</a></li>{%endfor%}</ul>
Or in Python code:
fromdjango.urlsimportreversefromdjango.httpimportHttpResponseRedirectdefredirect_to_year(request):# ...year=2006# ...returnHttpResponseRedirect(reverse('news-year-archive',args=(year,)))
If, for some reason, it was decided that the URLs where content for yearlyarticle archives are published at should be changed then you would only need tochange the entry in the URLconf.
In some scenarios where views are of a generic nature, a many-to-onerelationship might exist between URLs and views. For these cases the view nameisn’t a good enough identifier for it when comes the time of reversingURLs. Read the next section to know about the solution Django provides for this.
Naming URL patterns¶
In order to perform URL reversing, you’ll need to usenamed URL patternsas done in the examples above. The string used for the URL name can contain anycharacters you like. You are not restricted to valid Python names.
When you name your URL patterns, make sure you use names that are unlikelyto clash with any other application’s choice of names. If you call your URLpatterncomment, and another application does the same thing, there’sno guarantee which URL will be inserted into your template when you usethis name.
Putting a prefix on your URL names, perhaps derived from the applicationname, will decrease the chances of collision. We recommend something likemyapp-comment instead ofcomment.
URL namespaces¶
Introduction¶
URL namespaces allow you to uniquely reversenamed 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 wedid in the tutorial). Similarly, it also allows you to reverse URLs if multipleinstances of an application are deployed. In other words, since multipleinstances of a single application will share named URLs, namespaces provide away to tell these named URLs apart.
Django applications that make proper use of URL namespacing can be deployed morethan once for a particular site. For exampledjango.contrib.admin has anAdminSite class which allows you to easilydeploy more than one instance of the admin.In a later example, we’ll discuss the idea of deploying the polls applicationfrom the tutorial in two different locations so we can serve the samefunctionality 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. Everyinstance of a single application will have the same application namespace.For example, Django’s admin application has the somewhat predictableapplication namespace of
'admin'. - instance namespace
- This identifies a specific instance of an application. Instance namespacesshould be unique across your entire project. However, an instance namespacecan be the same as the application namespace. This is used to specify adefault instance of an application. For example, the default Django admininstance has an instance namespace of
'admin'.
Namespaced URLs are specified using the':' operator. For example, the mainindex page of the admin application is referenced using'admin:index'. Thisindicates a namespace of'admin', and a named URL of'index'.
Namespaces can also be nested. The named URL'sports:polls:index' wouldlook for a pattern named'index' in the namespace'polls' that is itselfdefined within the top-level namespace'sports'.
Reversing namespaced URLs¶
When given a namespaced URL (e.g.'polls:index') to resolve, Django splitsthe fully qualified name into parts and then tries the following lookup:
First, Django looks for a matchingapplication namespace (in thisexample,
'polls'). This will yield a list of instances of thatapplication.If there is a current application defined, Django finds and returns the URLresolver for that instance. The current application can be specified withthe
current_appargument to thereverse()function.The
urltemplate tag uses the namespace of the currently resolvedview as the current application in aRequestContext. You can override this default bysetting the current application on therequest.current_appattribute.Changed in Django 1.9:Previously, the
urltemplate tag did not use the namespace of thecurrently resolved view and you had to set thecurrent_appattributeon the request.If there is no current application. Django looks for a defaultapplication instance. The default application instance is the instancethat has aninstance namespace matching theapplicationnamespace (in this example, an instance of
pollscalled'polls').If there is no default application instance, Django will pick the lastdeployed instance of the application, whatever its instance name may be.
If the provided namespace doesn’t match anapplication namespace instep 1, Django will attempt a direct lookup of the namespace as aninstance namespace.
If there are nested namespaces, these steps are repeated for each part of thenamespace until only the view name is unresolved. The view name will then beresolved into a URL in the namespace that has been found.
Example¶
To show this resolution strategy in action, consider an example of two instancesof thepolls application from the tutorial: one called'author-polls'and one called'publisher-polls'. Assume we have enhanced that applicationso that it takes the instance namespace into consideration when creating anddisplaying polls.
fromdjango.conf.urlsimportinclude,urlurlpatterns=[url(r'^author-polls/',include('polls.urls',namespace='author-polls')),url(r'^publisher-polls/',include('polls.urls',namespace='publisher-polls')),]
fromdjango.conf.urlsimporturlfrom.importviewsapp_name='polls'urlpatterns=[url(r'^$',views.IndexView.as_view(),name='index'),url(r'^(?P<pk>\d+)/$',views.DetailView.as_view(),name='detail'),...]
Using this setup, the following lookups are possible:
If one of the instances is current - say, if we were rendering the detail pagein the instance
'author-polls'-'polls:index'will resolve to theindex page of the'author-polls'instance; i.e. both of the following willresult in"/author-polls/".In the method of a class-based view:
reverse('polls:index',current_app=self.request.resolver_match.namespace)
and in the template:
{%url'polls:index'%}
If there is no current instance - say, if we were rendering a pagesomewhere else on the site -
'polls:index'will resolve to the lastregistered instance ofpolls. Since there is no default instance(instance namespace of'polls'), the last instance ofpollsthat isregistered will be used. This would be'publisher-polls'since it’sdeclared last in theurlpatterns.'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 currentinstance (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 instancedeclared last inurlpatterns.
URL namespaces and included URLconfs¶
Application namespaces of included URLconfs can be specified in two ways.
Firstly, you can set anapp_name attribute in the included URLconf module,at the same level as theurlpatterns attribute. You have to pass the actualmodule, or a string reference to the module, toinclude(), not the list ofurlpatterns itself.
fromdjango.conf.urlsimporturlfrom.importviewsapp_name='polls'urlpatterns=[url(r'^$',views.IndexView.as_view(),name='index'),url(r'^(?P<pk>\d+)/$',views.DetailView.as_view(),name='detail'),...]
fromdjango.conf.urlsimportinclude,urlurlpatterns=[url(r'^polls/',include('polls.urls')),]
The URLs defined inpolls.urls will have an application namespacepolls.
Secondly, you can include an object that contains embedded namespace data. Ifyouinclude() a list ofurl() instances,the URLs contained in that object will be added to the global namespace.However, you can alsoinclude() a 2-tuple containing:
(<listofurl()instances>,<applicationnamespace>)
For example:
fromdjango.conf.urlsimportinclude,urlfrom.importviewspolls_patterns=([url(r'^$',views.IndexView.as_view(),name='index'),url(r'^(?P<pk>\d+)/$',views.DetailView.as_view(),name='detail'),],'polls')urlpatterns=[url(r'^polls/',include(polls_patterns)),]
This will include the nominated URL patterns into the given applicationnamespace.
The instance namespace can be specified using thenamespace argument toinclude(). If the instance namespace is not specified,it will default to the included URLconf’s application namespace. This meansit will also be the default instance for that namespace.
In previous versions, you had to specify both the application namespaceand the instance namespace in a single place, either by passing them asparameters toinclude() or by including a 3-tuplecontaining(<listofurl()instances>,<applicationnamespace>,<instancenamespace>).

