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.

See Cool 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 amapping between URL path expressions to Python functions (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 the internationalization 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_URLCONF setting, but if the incomingHttpRequest object has a urlconfattribute (set by middleware), its value will be used in place of theROOT_URLCONF setting.
  • Django loads that Python module and looks for the variableurlpatterns. This should be a sequence ofdjango.urls.path() and/or django.urls.re_path() instances.
  • Django runs through each URL pattern, in order, and stops at the firstone that matches the requested URL.
  • Once one of the URL patterns matches, Django imports and calls the givenview, which is a Python function (or a class-based view). The view gets passed the followingarguments:
    • An instance of HttpRequest.
    • If the matched URL pattern returned no named groups, then thematches from the regular expression are provided as positional arguments.
    • The keyword arguments are made up of any named parts matched by thepath expression, overridden by any arguments specified in the optionalkwargs argument to django.urls.path() ordjango.urls.re_path().
  • If no URL pattern matches, or if an exception is raised during anypoint in this process, Django invokes an appropriateerror-handling view. See Error handling below.

Example

Here’s a sample URLconf:

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. urlpatterns = [
  6. path('articles/2003/', views.special_case_2003),
  7. path('articles/<int:year>/', views.year_archive),
  8. path('articles/<int:year>/<int:month>/', views.month_archive),
  9. path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
  10. ]

Notes:

  • To capture a value from the URL, use angle brackets.
  • Captured values can optionally include a converter type. For example, use<int:name> to capture an integer parameter. If a converter isn’t included,any string, excluding a / character, is matched.
  • There’s no need to add a leading slash, because every URL has that. Forexample, it’s articles, not /articles.Example requests:

  • A request to /articles/2005/03/ would match the third entry in thelist. Django would call the functionviews.month_archive(request, year=2005, month=3).

  • /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/2003 would not match any of these patterns, because eachpattern requires that the URL end with a slash.
  • /articles/2003/03/building-a-django-site/ would match the finalpattern. Django would call the functionviews.article_detail(request, year=2003, month=3, slug="building-a-django-site").

Path converters

The following path converters are available by default:

  • str - Matches any non-empty string, excluding the path separator, '/'.This is the default if a converter isn’t included in the expression.
  • int - Matches zero or any positive integer. Returns an int.
  • slug - Matches any slug string consisting of ASCII letters or numbers,plus the hyphen and underscore characters. For example,building-your-1st-django-site.
  • uuid - Matches a formatted UUID. To prevent multiple URLs from mapping tothe same page, dashes must be included and letters must be lowercase. Forexample, 075194d3-6885-417e-a8a8-6c931e272f00. Returns aUUID instance.
  • path - Matches any non-empty string, including the path separator,'/'. This allows you to match against a complete URL path rather thana segment of a URL path as with str.

Registering custom path converters

For more complex matching requirements, you can define your own path converters.

A converter is a class that includes the following:

  • A regex class attribute, as a string.
  • A to_python(self, value) method, which handles converting the matchedstring into the type that should be passed to the view function. It shouldraise ValueError if it can’t convert the given value. A ValueError isinterpreted as no match and as a consequence a 404 response is sent to theuser.
  • A to_url(self, value) method, which handles converting the Python typeinto a string to be used in the URL.For example:
  1. class FourDigitYearConverter:
  2. regex = '[0-9]{4}'
  3.  
  4. def to_python(self, value):
  5. return int(value)
  6.  
  7. def to_url(self, value):
  8. return '%04d' % value

Register custom converter classes in your URLconf usingregister_converter():

  1. from django.urls import path, register_converter
  2.  
  3. from . import converters, views
  4.  
  5. register_converter(converters.FourDigitYearConverter, 'yyyy')
  6.  
  7. urlpatterns = [
  8. path('articles/2003/', views.special_case_2003),
  9. path('articles/<yyyy:year>/', views.year_archive),
  10. ...
  11. ]

Using regular expressions

If the paths and converters syntax isn’t sufficient for defining your URLpatterns, you can also use regular expressions. To do so, usere_path() instead of path().

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

Here’s the example URLconf from earlier, rewritten using regular expressions:

  1. from django.urls import path, re_path
  2.  
  3. from . import views
  4.  
  5. urlpatterns = [
  6. path('articles/2003/', views.special_case_2003),
  7. re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
  8. re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
  9. re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
  10. ]

This accomplishes roughly the same thing as the previous example, except:

  • The exact URLs that will match are slightly more constrained. For example,the year 10000 will no longer match since the year integers are constrainedto be exactly four digits long.
  • Each captured argument is sent to the view as a string, regardless of whatsort of match the regular expression makes.When switching from using path() tore_path() or vice versa, it’s particularly important to beaware that the type of the view arguments may change, and so you may need toadapt your views.

Using unnamed regular expression groups

As well as the named group syntax, e.g. (?P<year>[0-9]{4}), you canalso use the shorter unnamed group, e.g. ([0-9]{4}).

This usage isn’t particularly recommended as it makes it easier to accidentallyintroduce errors between the intended meaning of a match and the argumentsof the view.

In either case, using only one style within a given regex is recommended. Whenboth styles are mixed, any unnamed groups are ignored and only named groups arepassed to the view function.

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:

  1. from django.urls import re_path
  2.  
  3. urlpatterns = [
  4. re_path(r'^blog/(page-(\d+)/)?$', blog_articles), # bad
  5. re_path(r'^comments/(?:page-(?P<page_number>\d+)/)?$', comments), # good
  6. ]

Both patterns use nested arguments and will resolve: for example,blog/page-2/ will result in a match to blog_articles with twopositional arguments: page-2/ and 2. The second pattern forcomments will match comments/page-2/ with keyword argumentpage_number set to 2. The outer argument in this case is a non-capturingargument (?:…).

The blog_articles view needs the outermost captured argument to be reversed,page-2/ or no arguments in this case, while comments can be reversedwith either no arguments or a value for page_number.

Nested captured arguments create a strong coupling between the view argumentsand the URL as illustrated by blog_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.

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 to https://www.example.com/myapp/, the URLconfwill look for myapp/.

In a request to https://www.example.com/myapp/?page=3, the URLconf will lookfor myapp/.

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.

Specifying defaults for view arguments

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

  1. # URLconf
  2. from django.urls import path
  3.  
  4. from . import views
  5.  
  6. urlpatterns = [
  7. path('blog/', views.page),
  8. path('blog/page<int:num>/', views.page),
  9. ]
  10.  
  11. # View (in blog/views.py)
  12. def page(request, num=1):
  13. # Output the appropriate page of blog entries, according to num.
  14. ...

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, the page() function will use itsdefault argument for num, 1. If the second pattern matches,page() will use whatever num value was captured.

Performance

Each regular expression in a urlpatterns is compiled the first time it’saccessed. This makes the system blazingly fast.

Syntax of the urlpatterns variable

urlpatterns should be a sequence of path()and/or re_path() instances.

Error handling

When Django can’t find a match for the requested URL, or when an exception israised, Django invokes 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 on customizing 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:

Including other URLconfs

At any point, your urlpatterns can “include” other URLconf modules. Thisessentially “roots” a set of URLs below other ones.

For example, here’s an excerpt of the URLconf for the Django websiteitself. It includes a number of other URLconfs:

  1. from django.urls import include, path
  2.  
  3. urlpatterns = [
  4. # ... snip ...
  5. path('community/', include('aggregator.urls')),
  6. path('contact/', include('contact.urls')),
  7. # ... snip ...
  8. ]

Whenever Django encounters include(), it chops offwhatever 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 ofpath() instances. For example, consider this URLconf:

  1. from django.urls import include, path
  2.  
  3. from apps.main import views as main_views
  4. from credit import views as credit_views
  5.  
  6. extra_patterns = [
  7. path('reports/', credit_views.report),
  8. path('reports/<int:id>/', credit_views.report),
  9. path('charge/', credit_views.charge),
  10. ]
  11.  
  12. urlpatterns = [
  13. path('', main_views.homepage),
  14. path('help/', include('apps.help.urls')),
  15. path('credit/', include(extra_patterns)),
  16. ]

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:

  1. from django.urls import path
  2. from . import views
  3.  
  4. urlpatterns = [
  5. path('<page_slug>-<page_id>/history/', views.history),
  6. path('<page_slug>-<page_id>/edit/', views.edit),
  7. path('<page_slug>-<page_id>/discuss/', views.discuss),
  8. path('<page_slug>-<page_id>/permissions/', views.permissions),
  9. ]

We can improve this by stating the common path prefix only once and groupingthe suffixes that differ:

  1. from django.urls import include, path
  2. from . import views
  3.  
  4. urlpatterns = [
  5. path('<page_slug>-<page_id>/', include([
  6. path('history/', views.history),
  7. path('edit/', views.edit),
  8. path('discuss/', views.discuss),
  9. path('permissions/', views.permissions),
  10. ])),
  11. ]

Captured parameters

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

  1. # In settings/urls/main.py
  2. from django.urls import include, path
  3.  
  4. urlpatterns = [
  5. path('<username>/blog/', include('foo.urls.blog')),
  6. ]
  7.  
  8. # In foo/urls/blog.py
  9. from django.urls import path
  10. from . import views
  11.  
  12. urlpatterns = [
  13. path('', views.blog.index),
  14. path('archive/', views.blog.archive),
  15. ]

In the above example, the captured "username" variable is passed to theincluded 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.

The path() function can take an optional third argumentwhich should be a dictionary of extra keyword arguments to pass to the viewfunction.

For example:

  1. from django.urls import path
  2. from . import views
  3.  
  4. urlpatterns = [
  5. path('blog/<int:year>/', views.year_archive, {'foo': 'bar'}),
  6. ]

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 to include()

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

For example, these two URLconf sets are functionally identical:

Set one:

  1. # main.py
  2. from django.urls import include, path
  3.  
  4. urlpatterns = [
  5. path('blog/', include('inner'), {'blog_id': 3}),
  6. ]
  7.  
  8. # inner.py
  9. from django.urls import path
  10. from mysite import views
  11.  
  12. urlpatterns = [
  13. path('archive/', views.archive),
  14. path('about/', views.about),
  15. ]

Set two:

  1. # main.py
  2. from django.urls import include, path
  3. from mysite import views
  4.  
  5. urlpatterns = [
  6. path('blog/', include('inner')),
  7. ]
  8.  
  9. # inner.py
  10. from django.urls import path
  11.  
  12. urlpatterns = [
  13. path('archive/', views.archive, {'blog_id': 3}),
  14. path('about/', views.about, {'blog_id': 3}),
  15. ]

Note that extra options will always be passed to every 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 as reverse resolution of URLs, reverse URLmatching, reverse URL lookup, or simply URL reversing.

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

  • In templates: Using the url template 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:

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. urlpatterns = [
  6. #...
  7. path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
  8. #...
  9. ]

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:

  1. <a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
  2. {# Or with the year in a template context variable: #}
  3. <ul>
  4. {% for yearvar in year_list %}
  5. <li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
  6. {% endfor %}
  7. </ul>

Or in Python code:

  1. from django.http import HttpResponseRedirect
  2. from django.urls import reverse
  3.  
  4. def redirect_to_year(request):
  5. # ...
  6. year = 2006
  7. # ...
  8. return HttpResponseRedirect(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 use named 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 naming URL patterns, choose names that are unlikely to clash with otherapplications’ choice of names. If you call your URL pattern commentand another application does the same thing, the URL thatreverse() finds depends on whichever pattern is last inyour project’s urlpatterns list.

Putting a prefix on your URL names, perhaps derived from the applicationname (such as myapp-comment instead of comment), decreases the chanceof collision.

You can deliberately choose the same URL name as another application if youwant to override a view. For example, a common use case is to override theLoginView. Parts of Django and mostthird-party apps assume that this view has a URL pattern with the namelogin. If you have a custom login view and give its URL the name login,reverse() will find your custom view as long as it’s inurlpatterns after django.contrib.auth.urls is included (if that’sincluded at all).

You may also use the same name for multiple URL patterns if they differ intheir arguments. In addition to the URL name, reverse()matches the number of arguments and the names of the keyword arguments.

URL namespaces

Introduction

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 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 deployedmore than once for a particular site. For example django.contrib.adminhas an AdminSite class which allows you todeploy more than one instance of the admin. In alater example, we’ll discuss the idea of deploying the polls application fromthe tutorial in two different locations so we can serve the same functionalityto 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 matching application 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_app argument to the reverse()function.

The url template tag uses the namespace of the currently resolvedview as the current application in aRequestContext. You can override this default bysetting the current application on the request.current_app attribute.

  • If there is no current application, Django looks for a defaultapplication instance. The default application instance is the instancethat has an instance namespace matching the applicationnamespace (in this example, an instance of polls called '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 an application 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 the polls 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.

urls.py

  1. from django.urls import include, path
  2.  
  3. urlpatterns = [
  4. path('author-polls/', include('polls.urls', namespace='author-polls')),
  5. path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),
  6. ]

polls/urls.py

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. app_name = 'polls'
  6. urlpatterns = [
  7. path('', views.IndexView.as_view(), name='index'),
  8. path('<int:pk>/', views.DetailView.as_view(), name='detail'),
  9. ...
  10. ]

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:

  1. reverse('polls:index', current_app=self.request.resolver_match.namespace)

and in the template:

  1. {% 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 of polls. Since there is no default instance(instance namespace of 'polls'), the last instance of polls that isregistered will be used. This would be 'publisher-polls' since it’sdeclared 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 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 in urlpatterns.

URL namespaces and included URLconfs

Application namespaces of included URLconfs can be specified in two ways.

Firstly, you can set an app_name attribute in the included URLconf module,at the same level as the urlpatterns attribute. You have to pass the actualmodule, or a string reference to the module, to include(),not the list of urlpatterns itself.

polls/urls.py

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. app_name = 'polls'
  6. urlpatterns = [
  7. path('', views.IndexView.as_view(), name='index'),
  8. path('<int:pk>/', views.DetailView.as_view(), name='detail'),
  9. ...
  10. ]

urls.py

  1. from django.urls import include, path
  2.  
  3. urlpatterns = [
  4. path('polls/', include('polls.urls')),
  5. ]

The URLs defined in polls.urls will have an application namespace polls.

Secondly, you can include an object that contains embedded namespace data. Ifyou include() a list of path() orre_path() instances, the URLs contained in that objectwill be added to the global namespace. However, you can also include() a2-tuple containing:

  1. (<list of path()/re_path() instances>, <application namespace>)

For example:

  1. from django.urls import include, path
  2.  
  3. from . import views
  4.  
  5. polls_patterns = ([
  6. path('', views.IndexView.as_view(), name='index'),
  7. path('<int:pk>/', views.DetailView.as_view(), name='detail'),
  8. ], 'polls')
  9.  
  10. urlpatterns = [
  11. path('polls/', include(polls_patterns)),
  12. ]

This will include the nominated URL patterns into the given applicationnamespace.

The instance namespace can be specified using the namespace 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.