Using relative paths for Django template directories

Django's template dirs are specified as absolute paths in settings.py:

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

But since this is just Python code, it is relatively easy to specify relative paths (no pun intended). As described in this blog, add the following code to settings.py:

import os
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

And then in the TEMPLATE_DIRS section you can specify a relative path like this:

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'templates')
)

Comments

Good tip, thanks!

I've been using Django for a while, and had always obediently gone along with the inconvenience of using absolute paths in the TEMPLATE_DIRS setting.

Thanks for a concise demonstration of how to get around needing to continue doing this!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.