oeimhq
Last Updated: February 25, 2016
·
435
· rosatimatteo

Django per-environment specific settings

When starting a Django project, the settings.py file is not a feasible solution if you have to deploy your application on several environments.

One solution is to have a settings module in your root project directory, where you will pick the right settings file depending on the environment you are.

Here is how the settings module looks like

project_root
|__media
|__your_project
   |____init__.py
   |__urls.py
   |__wsgi.py
|__app1
|__app2
|__static
|__settings
   |____init__.py
   |__base.py
   |__local.py
   |__local.py.dist
   |__other_env.py
|__manage.py

Everything you will put in base.py will be considered as a enviroment-independent setting. Remember to adjust manage.py file and wsgi.py file to keep the right settings file

in manage.py, replace the rows immediately after if __name__ == "__main__"

env = os.environ.get('DJANGO_ENV') or 'local'
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", '.'.join(['settings', env]))

and the same thing for wsgi.py

Environment-specific files will have the following form, consider for example local.py

from .base import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# other settings here
# ...

Remember: exclude these env settings files from versioning ;) (keep a .dist file as a blueprint)