Use Environment Variables in Django - Efficient Way

Use Environment Variables in Django - Efficient Way

August 16, 2022
Infrastructure
env

If you stil not use environment variables to configure your Django application - dont wait, do it! I’ll tell you efficient way to use environment variables in the Django’s settings.py file which allows you to set environment variables via the server environment and in the .env file for local development.

Installation #

You need to install python-decouple package from PyPi.

pip install python-decouple
poetry add python-decouple
pipenv install python-decouple

Usage in settings.py #

Import module and modify settings statments to get it from environment, set it’s casting type and fallback default value if it applicable.

from decouple import config
DEBUG = config('DEBUG', cast=bool, default=False)
ALLOWED_HOSTS = ['localhost', '127.0.0.1', config('ALLOWED_HOSTS', default='localhost')]
SECRET_KEY = config('SECRET_KEY', default='secret_key_default')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME', default='db_name'),
        'USER': config('DB_USER', default='db_user'),
        'PASSWORD': config('DB_PASS', default=''),
        'HOST': config('DB_HOST', default='127.0.0.1'),
        'PORT': config('DB_PORT', default='5432'),
    },
}

This way settings will be pulled from the environment or .env file based on setup.

Comments