Using environment variables in your Django 3 Project

One of the recurring mistakes in a new django app is to leave the settings.py as generated when you create your app and then store it on GitHub (or a similar repository) where your credentials will be easily available to others. For instance your secret key (which is used for sessions, cookies and all cryptographic signing) and other sensitive data like database credentials etc. should not be shared in any repository (even if is a private one). It should only leave your computer for the deployment in the live server.

To achieve this I recommend the package Django-environ with the following setup:

first install the package with

pip3 install Django-environ

(or just pip install if you have configured pip to use Python 3)

in your settings.py add the following at the top after import os

import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
# reading .env file


now you can then replace the sensitive information from your settings.py in a similar way of the following example:

    DEBUG = env('DEBUG')
'default': env.db(),

This configuration assumes that you have a file called simply .env in the root of your project. This file should be added to .gitignore and not committed in a git repository, or shared with anyone what you can however commit in your git repository is a file called .env_sample (or anything you like as long as it is not .env by itself) with a sample of the configuration like this:

DATABASE_URL=mysql://username:[email protected]:port/dbname?charset=utf8mb4

in the live server you can should turn DEBUG=False to avoid to expose any debugging information once the site is live.

To generate a secret key you can just launch python on console and use the following:

from django.core.management.utils import get_random_secret_key

and you can then add it to the .env file.

If you already published the settings.py somewhere without using environment variables you can change your private key and the database login credentials (not applicable to SQLite as it is file based)..

Using environment variables might seem as an extra step but is a very important one to insure the integrity of your data, both for yourself and your users..

made with ❤ī¸ by david.dev 2023 RSS Feed