Paths in Django

I’ve been using Django on and off for about 6 months now, and one of the biggest annoyances with it is that you are instructed to put absolute paths into your file. This is fairly horrible, as the path is almost certainly going to be different between your development and production machines and therefore a nightmare to maintain. For some reason, I decided to google it tonight and found the solution within seconds, what an idiot…

The trick is to use paths relative to ( __file__ is the current file ). Obvious, can’t believe I didn’t think of it myself. Especially since Zend Framework in PHP does it the same way. I’ll blame being new to python. Disappointing the official docs don’t suggest this:

import os

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))

MEDIA_ROOT = os.path.join(PROJECT_DIR, ‘media’)
os.path.join(PROJECT_DIR, ‘templates/’),

Now, if I can stop having to put the name of the top-level project directory – import folder.file – in almost all of my source files, I’ll be happy.


Turns out you don’t have to put the name of the project in every import statement, just another mistake in the default project setup wizard!