Dynamic Paths in Django

November 24, 2010

Here's how to avoid storing hard coded path names in Django.

manage.py

In manage.py, change the top of the file to setup sys.path like this:

import os,sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..'))
sys.path.append(PROJECT_DIR)

This will automatically add the directory above the one with settings.py in to the PYTHONPATH.

settings.py

You can do the same with the settings.py file. Add this at the top:

import os,sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..'))

and now you can refer to PROJECT_DIR within, for example, TEMPLATE_DIRS:

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.
    '%s/bbr/templates' % PROJECT_DIR,
)