How to separate your settings.py file for different environments in Django projects.


This is another practice that I like to implement in my Django projects, it is a safe way to have many apps and customized variables according your project environments (local development, testing, integration, production, etc).

Step 1: Create a directory inside your project folder named settings, and create a __init__.py file inside it.

- manage.py
- your_project
-- settings
--- __init__.py
-- __init__.py
-- settings.py
-- urls.py
-- wsgi.py

Step 2: Rename your current settings.py file to base.py and move inside settings (new folder from step 1)

- manage.py
- your_project
-- settings
--- __init__.py
--- base.py
-- __init__.py
-- urls.py
-- wsgi.py

Step 3: Create local.py file (e.g) to use it in your local environment, and then import everything from base:

- manage.py
- your_project
-- settings
--- __init__.py
--- base.py
--- local.py
-- __init__.py
-- urls.py
-- wsgi.py
# settings/local.py
from .base import *

Step 4: Add changes and remove variables from base.py according to your requirements (e.g).

# settings/local.py
from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

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

Step 5 (Optional): If you use virtualenvwrapper do not forget to add the following variable to your postactivate file:

export DJANGO_SETTINGS_MODULE=YourProject.settings.local

 Step 6 (Optional): If you have several virtualenv environments in your computer, you should add the following command to your postdeactivate file:

unset DJANGO_SETTINGS_MODULE

 

Now you can add applications according to your requirements, for example just add django-debug-toolbar to local development, etc.

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.