Django Settings Using BASE_DIR to ensure app portability

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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")
STATICFILES_DIRS = [
    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 project.settings.dev, 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')
STATICFILES_DIRS = [
    BASE_DIR.child('static'),
]


Got any Django Question?