[Django]-Best way to handle different configuration/settings based on environment in Django project

4👍

As an answer to the question:

Is DEBUG == False supposed to mean that the app is running in production environment?

DEBUG is a configuration that you define in your setting.py file.

  • If set to True, in case of un-handled exception it displays the complete stack-trace along with the values of all the declared variables.

  • If set to False, your server just returns the 500 status code without any stack-trace.

In production, you must have DEBUG set to False in order to prevent potential risk of security breach, and other information which you wouldn’t want your user to know.


In order to use different settings configuration on different environment, create different settings file. And in your deployment script, start the server using --settings=<my-settings.py> parameter, via which you can use different settings on different environment.

Benefits of using this approach:

  1. Your settings will be modular based on each environment

  2. You may import the master_settings.py containing the base configuration in the environmnet_configuration.py and override the values that you want to change in that environment.

  3. If you have huge team, each developer may have their own local_settings.py which they can add to the code repository without any risk of modifying the server configuration. You can add these local settings to .gitnore if you use git or .hginore if you Mercurial for Code Version Control. That way local settings won’t even be the part of actual code base keeping it clean.

0👍

Use django-configurations to define a some alternative configurations and set the environment variable DJANGO_CONFIGURATION on each machine running the code to choose one.

You’re free to define the classes however you’d like, but I’d recommend defining a Common class, which everything inherits from, and then Dev, Test, and Prod classes.

Anything involving system configuration should be pulled from environment variables (eg database connection, cache connection etc).

Have fun!

0👍

To add to @anonymous answer, here’s the script (manage.sh) I came up with:

#!/usr/bin/env bash
DIR=$(dirname -- "$(readlink -f -- "$0")")
export PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}"
if [ -e <app>/local_settings.py ]; then
    export DJANGO_SETTINGS_MODULE=<app>.local_settings
else
    export DJANGO_SETTINGS_MODULE=<app>.settings
fi
django-admin "$@"

It uses <app>.local_settings if exists. Otherwise it falls back to <app>.settings.

Alternatively, you can just edit your manage.py.

👤x-yuri

Leave a comment