~ / blog / development / use-environment-variables-in-django-efficient-way
django 2022-08-16·1 min read

Use Environment Variables in Django - Efficient Way

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.

shell
pip install django-database-prefix

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.

python
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.