0
0
DjangoHow-ToBeginner · 3 min read

How to Use Environment Variables in Django for Configuration

In Django, use the os.environ dictionary to access environment variables by importing os. For better management, use the python-dotenv package to load variables from a .env file into your settings.
📐

Syntax

To use environment variables in Django, import the os module and access variables with os.environ.get('VARIABLE_NAME'). This returns the value or None if the variable is not set.

Example parts:

  • import os: imports the module to access environment variables.
  • os.environ.get('VAR'): fetches the value of the environment variable named 'VAR'.
  • Use a default value by adding a second argument, e.g., os.environ.get('VAR', 'default').
python
import os

secret_key = os.environ.get('DJANGO_SECRET_KEY', 'default-secret-key')
debug_mode = os.environ.get('DJANGO_DEBUG', 'False') == 'True'
💻

Example

This example shows how to load environment variables from a .env file using python-dotenv and use them in Django's settings.py.

It demonstrates setting a secret key and debug mode securely without hardcoding them.

python
from dotenv import load_dotenv
import os

# Load variables from .env file
load_dotenv()

# Access environment variables
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True'

# Example usage
print(f"Secret Key: {SECRET_KEY}")
print(f"Debug Mode: {DEBUG}")
Output
Secret Key: supersecretkey123 Debug Mode: True
⚠️

Common Pitfalls

  • Not setting environment variables before running Django causes None or errors.
  • Hardcoding secrets in settings.py risks security leaks.
  • Forgetting to load the .env file when using python-dotenv means variables won't be available.
  • Using os.environ['VAR'] without get can raise KeyError if the variable is missing.
python
import os

# Wrong: raises error if variable missing
# SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

# Right: safe access with default
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'fallback-key')
📊

Quick Reference

Tips for using environment variables in Django:

  • Use os.environ.get() to safely access variables.
  • Use python-dotenv to load .env files during development.
  • Never commit .env files with secrets to version control.
  • Set environment variables in your deployment environment (e.g., server, Docker, CI/CD).
  • Convert string values to correct types (e.g., booleans) as needed.

Key Takeaways

Use os.environ.get('VAR') to safely read environment variables in Django settings.
Load .env files with python-dotenv during development to keep secrets out of code.
Avoid hardcoding sensitive data like secret keys directly in settings.py.
Always set environment variables in your production environment securely.
Convert environment variable strings to proper types before use (e.g., booleans).