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 include, url

urlpatterns = [
# …
url(r’^community/’, include(‘django_website.aggregator.urls’)),
url(r’^contact/’, include(‘django_website.contact.urls’)),
# …
]

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(), 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 by using a list of url() instances. For example, consider this URLconf:

from django.conf.urls import include, url
from apps.main import views as main_views
from credit import views as credit_views

extra_patterns = [
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 the credit.views.report() Django view. This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example, consider this URLconf:

from django.conf.urls import url
from . import views

urlpatterns = [
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 grouping the suffixes that differ:

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

urlpatterns = [
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, so the fol\
lowing example is valid:

# In settings/urls/main.py
from django.conf.urls import include, url

urlpatterns = [
url(r’^(?P<username>\w+)/reviews/’, include(‘foo.urls.reviews’)),
]

# In foo/urls/reviews.py
from django.conf.urls import url
from . import views

urlpatterns = [
url(r’^$’, views.reviews.index),
url(r’^archive/$’, views.reviews.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. The django.conf.urls.url() function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function. For example:

from django.conf.urls import url
from . import views

urlpatterns = [
url(r’^reviews/(?P<year>[0-9]{4})/$’,
views.year_archive,
{‘foo’: ‘bar’}),
]

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

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
from django.conf.urls import include, url

urlpatterns = [
url(r’^reviews/’, include(‘inner’), {‘reviewid’: 3}),
]

# inner.py
from django.conf.urls import url
from mysite import views

urlpatterns = [
url(r’^archive/$’, views.archive),
url(r’^about/$’, views.about),
]

Set two:
# main.py
from django.conf.urls import include, url
from mysite import views

urlpatterns = [
url(r’^reviews/’, include(‘inner’)),
]

# inner.py
from django.conf.urls import url

urlpatterns = [
url(r’^archive/$’, views.archive, {‘reviewid’: 3}),
url(r’^about/$’, views.about, {‘reviewid’: 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.

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 to avoid hard-coding 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 import url
from . import views

urlpatterns = [
#…
url(r’^reviews/([0-9]{4})/$’, views.year_archive,
name=’reviews-year-archive’),
#…
]

According to this design, the URL for the archive corresponding to year nnnn is /reviews/nnnn/. You can obtain these in template code by using:

<a href=”{% url ‘reviews-year-archive’ 2012 %}”>2012 Archive</a>
{# Or with the year in a template context variable: #}

<ul>
{% for yearvar in year_list %}
<li><a href=”{% url ‘reviews-year-archive’ yearvar %}”>{{
yearvar }} Archive</a></li>
{% endfor %}
</ul>

Or in Python code:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def redirect_to_year(request):
# …
year = 2012
# …
return HttpResponseRedirect(reverse(‘reviews-year-archive’, args=(year,)))

If, for some reason, it was decided that the URLs where content for yearly review 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.

Naming URL Patterns

In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. The string used for the URL name can contain any characters you like. You are not restricted to valid Python names. 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

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. 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. 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 members:reviews:index would look for a pattern named “index” in the namespace “reviews” that is itself defined within the top-level namespace “members”.
Reversing Namespaced URLs
When given a namespaced URL (e.g. “reviews: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, “reviews”). 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 request. Applications that expect to have multiple deployments should set the current_app attribute on the request being processed.
  • 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 reviews called “reviews”).
  • If there is no default application instance, Django will pick the last deployed instance of the application, whatever its instance name may be.
  • If the provided namespace doesn’t match an application namespace in step 1, Django will attempt a direct lookup of the namespace as an instance namespace.

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.
URL Namespaces and Included URLconfs
URL namespaces of included URLconfs can be specified in two ways. Firstly, you can provide the application and instance namespaces as arguments to include() when you construct your URL patterns. For example:

url(r’^reviews/’, include(‘reviews.urls’, namespace=’author-reviews’, app_name=’revie\
ws’)),

This will include the URLs defined in reviews.urls into the application namespace ‘reviews’, with the instance namespace ‘author-reviews’. 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:

(<list of url() instances>, <application namespace>, <instance namespace>)

For example:

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

reviews_patterns = [
url(r’^$’, views.IndexView.as_view(), name=’index’),
url(r’^(?P<pk>\d+)/$’, views.DetailView.as_view(), name=’detail’),
]

url(r’^reviews/’, include((reviews_patterns, ‘reviews’, ‘author-reviews’))),

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(reviews_patterns, ‘reviews’, ‘author-reviews’), Django won’t throw an error but due to the signature of include(), ‘reviews’ will be the instance namespace and ‘author-reviews’ will be the application namespace instead of vice versa.

Back to Tutorial

Introduction to MBean Descriptor
Adding MBean descriptions

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?