A better way to set your Django template directory setting — dynamically

When using Django you must specify where the framework can find your templates by setting the TEMPLATE_DIRS setting in settings.py.  Typically I just set it to a static path, but recently came across a great tip about how to set it dynamically (thanks to The Definitive Guide to Django).

In settings.py, I would usually specify something like this:

 Python |  copy code |? 
1
TEMPLATE_DIRS = (
2
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
3
    # Always use forward slashes, even on Windows.
4
    # Don't forget to use absolute paths, not relative paths.
5
    "C:/MyDjango/myproject/mytemplates"
6
)

But there is a much better way to specific this such that it is dynamic:

 Python |  copy code |? 
1
import os.path
2
 
3
TEMPLATE_DIRS = (
4
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
5
    # Always use forward slashes, even on Windows.
6
    # Don't forget to use absolute paths, not relative paths.
7
    os.path.join(os.path.dirname(__file__), 'mytemplates').replace('\\','/'),
8
)

This solution uses os.path.dirname(__file__), which gets the name of the directory that the current file resides in using __file__, which references the current Python module which the code lives in (settings.py).  The appropriate sub-directory mytemplates is appended using os.path.join. Finally, the .replace('\\','/') replaces any pesky backslashes with the required forward slashes.

A couple notes:

  1. Be sure to include the trailing comma at the end of the line, as you are able to specify more than one template directory and Django will not be happy without the comma.
  2. You must import os.path to have access to the appropriate Python functions used to assemble the path.

The flexibility of this solution should be immediately apparent, allowing for easily moving your project around, including to production, without having to update your template directory.


Leave a Reply