Managing Environment Variables and Secrets in Django
## Never Hardcode Secrets
Hardcoded secrets in source code are the #1 cause of credential leaks. Use environment variables at every layer.
## python-decouple
```bash
pip install python-decouple
```
```python
# settings.py
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
DB_PASSWORD = config('DB_PASSWORD')
```
## .env File (local dev only)
```env
SECRET_KEY=local-dev-secret-key-change-in-production
DEBUG=True
DB_PASSWORD=localpassword
```
**Never commit `.env` to git.** Add it to `.gitignore`.
## Production: No .env File
In production, inject variables via the platform:
- **Docker Compose**: `env_file: .env` (file lives on server, not in repo)
- **Docker run**: `--env-file .env`
- **CI/CD**: Protected + Masked pipeline variables
## Secret Rotation
Rotate secrets immediately if:
- A developer leaves the team
- A .env file is accidentally committed
- Any breach is suspected
Use `git filter-branch` or BFG Repo Cleaner to purge secrets from git history.