Typically, Django sites are designed with the assumption that they’ll have a domain or subdomain to themselves. Often times this is fine, but if you’re developing a web application designed for redistribution, sometimes you can’t make that assumption.

During development of Review Board, many of our users wanted the ability to install Review Board into a subdirectory of one of their domains, rather than a subdomain.

There’s a few rules that are important when making your site relocatable:

Always use MEDIA_URL when referring to your media directory, so that people can customize where they put their media files.

when referring to your media directory, so that people can customize where they put their media files. Don’t hard-code URLs in templates. Use the {% url %} tag or get_absolute_url() when possible.

These solve some of the issues, but doesn’t address relocating a Django site to a subdirectory.

Djblets fills in this gap by providing a special URL handler designed to act as a prefix for all your projects’ URLs. To make use of this, you need to modify your settings.py file as follows:

settings.py

TEMPLATE_CONTEXT_PROCESSORS = ( ... 'djblets.util.context_processors.siteRoot', ) SITE_ROOT_URLCONF = 'yourproject.urls' ROOT_URLCONF = 'djblets.util.rooturl' SITE_ROOT = '/'

SITE_ROOT specifies where the site is located. By default, this should be “/”, but this can be changed to point to any path. For example, “/myproject/”. Note that it should always have a leading and a trailing slash.

The custom template context processor ( djblets.util.context_processors.siteRoot ) will make SITE_ROOT accessible to templates.

SITE_ROOT should be used in templates when you need to refer to URLs that aren’t designed to respect SITE_ROOT (such as User.get_absolute_url ). Your own custom applications should always respect SITE_ROOT whenever providing a URL.

ROOT_URLCONF is typically what you would set to point to your project’s URL. However, in this case, you’ll be pointing it to djblets.util.rooturl . This in turn will forward all URLs to your project’s handler, defined in SITE_ROOT_URLCONF .

This is all you need to have a fully relocatable Django site!

To sum up:

Add djblets.util.context_processors.siteRoot to your TEMPLATE_CONTEXT_PROCESSORS . Set SITE_ROOT_URLCONF to your project’s URL handler. Set ROOT_URLCONF to ‘djblets.util.rooturl’ Prefix any URLs with SITE_ROOT in your templates, unless the URL would already take SITE_ROOT into account.

This is functionality that will hopefully make its way into Django at some point. For now, you have an easy way of unrooting your Django project.