.env FilesStoring 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.
.env files keep secrets outside version controlpython-dotenv loads variables automatically.env files use a simple key-value format. Django accesses them using os.getenv().
# Install python-dotenv package
pip install python-dotenv
# 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 .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")
}
}
# Prevent committing secrets
.env
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.
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 files.env filesettings.py