← Back to Chapters

Managing Secrets in Django with .env Files

? Managing Secrets in Django with .env Files

? Quick Overview

Storing sensitive information such as API keys, database credentials, and secret keys directly in source code is unsafe. Using .env files allows Django applications to keep secrets secure, configurable, and environment-specific.

? Key Concepts

  • Environment variables store sensitive configuration values
  • .env files keep secrets outside version control
  • python-dotenv loads variables automatically

? Syntax / Theory

.env files use a simple key-value format. Django accesses them using os.getenv().

? Code Examples

Install python-dotenv

? View Code Example
# Install python-dotenv package
pip install python-dotenv

Create .env File

? View Code Example
# Environment variables stored securely
DJANGO_SECRET_KEY=your_secret_key_here
DEBUG=True
DATABASE_URL=postgres://user:password@localhost:5432/mydb
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key

Load Variables in settings.py

? View Code Example
# Load .env variables into Django settings
import os
from dotenv import load_dotenv

load_dotenv()

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY")
DEBUG = os.getenv("DEBUG", False)

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.getenv("DB_NAME"),
"USER": os.getenv("DB_USER"),
"PASSWORD": os.getenv("DB_PASSWORD"),
"HOST": os.getenv("DB_HOST"),
"PORT": os.getenv("DB_PORT", "5432")
}
}

.gitignore Protection

? View Code Example
# Prevent committing secrets
.env

? Live Explanation

When Django starts, load_dotenv() reads the .env file and injects values into the environment. These values are then accessed safely without exposing secrets in code.

? Interactive Concept

Use the simulator below. Edit the .env file on the left, then click Load Variables to see how Python reads them on the right.

? .env File (Editable)

? Python Output (os.getenv)

// Waiting for load...

? Use Cases

  • Storing API keys
  • Database credentials
  • Third-party service secrets
  • Different configs for dev & production

✅ Tips & Best Practices

  • Never commit .env files
  • Rotate secrets regularly
  • Use strong, random keys
  • Use secret managers in production

? Try It Yourself

  • Create a .env file
  • Load variables in settings.py
  • Switch environments dynamically