DEV Community

Cover image for How to Keep Configuration Secrets out of a Django Project

Posted on

How to Keep Configuration Secrets out of a Django Project

It is best practice to hide your configuration details and not include them in version control for the sake of security and independence of project instance. Getting straight to the point here is how to do it using python decouple library.

Quick Summary

  1. Install decouple pip install python-decouple or [].
  2. Create file named .env or .ini under the route of your project.
  3. Add ignore for .env if you are using git.
  4. Retrieve the settings by importing decouple into the file and replacing variables to hide with config. 5 . Test the application

Detailed Steps

This is how our initial exposed looks like before exclusion.

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '3izb^ryglmyscret_key_here'
DEBUG = True
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'HELLO_DJANGO',
        'USER': 'TINO',
        'PASSWORD': 'thepasswordhere',
        'HOST': '',
        'PORT': '0000',
Enter fullscreen mode Exit fullscreen mode

1. Installing decouple


pip install python-decouple

or if you prefer downloading []

2. Create .env file

Add variables to hide or exclude by copying values from making sure you do not include quotes("").

Enter fullscreen mode Exit fullscreen mode

3. Ignoring .env from version control(git)

Go into your gitignore file and add .env as below

# Environments

Enter fullscreen mode Exit fullscreen mode

This will make sure our file with variables is not tracked by the source control.

4. Retrieve the settings or values on variables set in the .env file

Import config from decouple as below and reference variables as strings

from decouple import config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = config('DEBUG', cast=bool) #NB casting here for boolean
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': '',
Enter fullscreen mode Exit fullscreen mode

Please Note: On non string values we need to cast to the type e.g

DEBUG = ('DEBUG', cast=bool)

as DEBUG expects boolean True or False

5. Test to see if your application still run the same


py runserver

to make sure your application still run smoothly.

I have tried to go straight to the point for easier implementation. My motivation to write this down was the struggle I had to find similar information which is helpful. Feel free to suggest different implementations or suggestions.

Happy Coding!!!

Top comments (0)