Dynamic paths for lazy people

Once your Django project has to run on multiple machines, the absolute paths in settings.py will drive you nuts.

A suggested solution to enhance portability (in German) is to define a PROJECT_ROOT.

import os
PROJECT_ROOT = os.path.dirname(__file__)

And then define absolute paths like this:

MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media')
TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

The downside is, typing os.path.join(PROJECT_ROOT,'foo') twice over and over again, will probably incur the wrath of the DRY gods. But don’t despair, we can do better:

import os
PROJECT_ROOT = os.path.dirname(__file__)
p = lambda *x: os.path.join(PROJECT_ROOT,*x)

Use it like this:

MEDIA_ROOT = p('static')
TEMPLATE_DIRS = (
    p('templates'),
)
MY_NESTED_PATH = p('x','y')

One thought on “Dynamic paths for lazy people

  1. Hey, the tip on using a lambda function to adhere to DRY principles is killer!