Mr. Editor-in-chief Mr. Editor-in-chief August 13, 2020 Updated April 24, 2026

How to Use Python Decouple Library for Django Application

Python Decouple is a great library that helps you strictly separate the settings parameters from your source code.

Installation
pip install python-decouple
Simply create a .env text file in your repository’s root directory in the form:
DEBUG=True
ALLOWED_HOSTS=localhost, 127.0.0.1, 192.168.1.202
DB_NAME=dbname
DB_USER=dbadmin
DB_PASS=password
DB_HOST=localhost
Use the env variables in your settings.py
from decouple import config

...
DEBUG = config('DEBUG', cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config('DB_NAME'), 
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASS'),
        'HOST': config('DB_HOST'),
    }
}
...