Deploy Django on a subdirectory (or a subpath) with mod_python

It doesn’t matter for how long you’ve been using Django – as much as you think you know it, at some point Django will surprise you transforming simple tasks into issues taking hours to be solved. I’ve never had the need to deploy a Django instance anywhere but the root of the domain name (e.g. Till last weekend, when I spent almost two hours to figure out how to do it without making a mess of the module (configuring Apache and mod_wsgi to serve a subpath was straightforward and it’s not covered by this article).

Actually Django does a really good job handling URL prefixes and, to be honest, I wouldn’t write these lines if I didn’t make use of the bittersweet Django Admin. AFAIK, problems arise in the following:

  • Your webserver does not set SCRIPT_NAME environment variable
  • Using the django-admin
  • Using {% url %} template tag
  • Using @login_required decorator

For the latter there’s a quick solution: set LOGIN_URL and LOGOUT_URL variables in your with the desired url path. In all the other cases, you’ve to play with the SCRIPT_NAME environment variable,  defined in CGI standard, which holds the request URL’s path which points at the application target. Well hidden (IMHO) at the bottom of this page you can find a quick and clean solution to manually set the SCRIPT_NAME variable: just define FORCE_SCRIPT_NAME in your, e.g. FORCE_SCRIPT_NAME=’/myapp’ without the trailing slash. That’s all.