Last Updated: April 05, 2017
·
925
· sobolevn

Managing Django Settings

Before you start you will need to install django-split-settings with pip install django-split-settings. This helper provides a user-friendly interface to store your settings in different files. Let’s look at the example. Imagine you have an existing project with django, postgres, redis , rq, and emails.

That’s what your files would look like after adopting django-split-settings and some manual restructuring:

your_project/settings/
├── __init__.py
├── components
│   ├── __init__.py
│   ├── database.py
│   ├── common.py
│   ├── emails.py
│   ├── rq.py
└── environments
    ├── __init__.py
    ├── development.py
    ├── local.py.template
    ├── production.py
    └── testing.py

That’s a clear separation of the settings based on two factors: what component they are configuring and at what environment we are working right now. And the flexibility of the library allows you to have any structure you want, not just the one described here.
In our settings/__init__.py we can define any logic we want. Basically, we would just define what kind of components we would like to use and select the environment. Here’s an example, we use in production for all our projects:

"""
This is a django-split-settings main file.
For more information read this:
https://github.com/sobolevn/django-split-settings

Default environment is `developement`.
To change settings file:
`DJANGO_ENV=production python manage.py runserver`
"""

from split_settings.tools import optional, include
from os import environ

ENV = environ.get('DJANGO_ENV') or 'development'

base_settings = [
    'components/common.py',  # standard django settings
    'components/database.py',  # postgres
    'components/rq.py',  # redis and redis-queue
    'components/emails.py',  # smtp

    # You can even use glob:
    # 'components/*.py'

    # Select the right env:
    'environments/%s.py' % ENV,
    # Optionally override some settings:
    optional('environments/local.py'),
]

# Include settings:
include(*base_settings)

And that’s it. Our application would run as usual. We have achieved multiple goals with so few lines of code:

  1. We now have separated settings based on what they configure. Gaining readability and maintainability
  2. We now have separated settings based on environment
  3. We now have optional local settings with now dirty hacks
  4. We did not have to do any refactoring except just some basic restructuring

Read full article: https://medium.com/wemake-services/managing-djangos-settings-e2b7f496120d