django organization and templates

I'm building a django project to manage the research I'm doing on optimization. (I'll update this with a link when it's functional enough that a link would be useful). The project consists of a number of apps, each with their own models, views, and templates. I want the whole project to have the same look and feel, though, so I'd like all of the app templates to use a project-wide css file, and to extend a project-wide base template. Here's what I've tried, and how it works.

For simplicity, let's talk about a project (called optimization) with two apps (called code and experiments). I'd like the relevant parts of the directory structure to look like this:

optimization/
----code/
--------templates/
------------code_base.html
------------code_module.html
------------code_module_list.html
----experiments/
--------templates/
------------exp_base.html
------------exp_setup.html
------------exp_results.html
----templates/
--------base.html

In this scenario, code_module.html extends code_base.html, which extends base.html. The project-wide base template base.html contains the site-wide navigation, css, and javascript, as well as the general layout. Each app base template modifies the navigation to indicate which section of the site the user is viewing, and sets up the basis of interaction with the data relevant to that app by defining a default-for-this-app content block.

So far so good; this kind of modularity is explicitly within the design philosophy of django, and is actually not that hard to accomplish. The key steps are:

  1. Include optimization/templates in the TEMPLATE_DIRS variable, and
  2. Include django.template.loaders.app_directories.Loader in TEMPLATE_LOADERS

That's essentially it. There are two more caveats, though (or at least, two that I've run up against so far):

  1. Use absolute, rather than relative paths when adding directories to TEMPLATE_DIRS. This may require a difference between development and production settings, so keep an eye on that.
  2. If you're using generic views, the default template location will be appname/templatename.html. Since I wanted to keep the templates for each app under the template directory of that app, this meant that django was looking for the templates in, for example optimization/codebase/templates/codebase/, which offended my sense of aesthetics. It's reasonably easy to get around this, though, by passing the actual location of the desired template to your generic view in urls.py.

Comments are disabled for this post