Django Settings Using BASE_DIR to ensure app portability


It's a bad idea to hard code paths in your application. One should always use relative urls so that your code can work seamlessly across different machines. The best way to set this up is to define a variable like this

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

Then use this BASE_DIR variable to define all your other settings.

TEMPLATE_PATH = os.path.join(BASE_DIR, "templates")
    os.path.join(BASE_DIR, "static"),


And so on. This ensures that you can port your code across different machines without any worries.

However, os.path is a bit verbose. For instance if your settings module is, you will have to write:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

An alternative is to use the unipath module (which you can install with pip install unipath).

from unipath import Path

BASE_DIR = Path(__file__).ancestor(2)  # or ancestor(3) if using a submodule

TEMPLATE_PATH = BASE_DIR.child('templates')