Django Settings Best Practice#

Two minute read.


Although there are many ways to configure the Django settings file structures, there is a commonality in many experienced developers’ approaches or preferred guidelines.

  1. Keep Secret keys out of Version Control.

  2. Version control settings.

  3. Follow The 12 Factor App [1] principles of storing Config.

  4. Do not repeat yourself.

  5. Keep Secret keys out of Version Control [2].

The 12 Factor guideline focus of this discussion is number three Config.

By following this guideline, we ensure strict separation between configuration settings and code.

Extract from 12 Factor Config: [3]#

An app’s config is everything likely to vary between deploys (staging, production, developer environments, etc.).

A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment without compromising any credentials.

Naming Conventions#

Poor naming practices can lead to potential errors and lost time. The result can often be frustrating.

Naming variables and settings is a challenging part of development. Following this simple guide for your custom project settings can make this a little easier:

  1. Give meaningful names to your settings.

  2. Use the project name as a prefix to your custom project settings.

  3. Write meaningful descriptions for your settings in the comments.

A meaningful setting name with comments.

# The default widget colour.
# Accepts a hex colour value.
MY_DJANGO_PROJECT_WIDGET_DEFAULT_COLOUR = #ff0000

Settings Files Structure#

From the outset, having a suitable configuration file structure has many benefits as the project grows. Some key benefits are:

  1. Separation of concerns; see file structure below.

  2. The settings are DRY [4].

  3. Eliminate copy and paste of settings.

  4. Eliminate errors with local dev settings breaking production.

  5. The settings file size is smaller and more manageable.

Django Cookiecutter will follow the settings file layout described in Two Scoops of Django 3.x [5].

Settings File Structure#
 config
  └── settings
       ├── __init__.py
       ├── base.py
       ├── local.py
       ├── production.py
       ├── staging.py
       └── test.py

Footnotes