Configuration
settings.py
Keep all project-wide configuration in settings.py. Organize settings into logical sections (e.g., database, installed apps, middleware, templates, static files, authentication).
- Use uppercase variable names for settings.
- Avoid hardcoding secrets or environment-specific values in
settings.py.
Example:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST', 'localhost'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
}
Environment Variables
Store secrets and environment-specific configuration in environment variables. Use a .env file and the python-dotenv or django-environ package to load variables.
- Never commit secrets or sensitive config to version control.
- Use environment variables for database credentials, secret keys, API keys, and debug flags.
Example:
# .env
DB_NAME=mydatabase
DB_USER=myuser
DB_PASSWORD=supersecret
SECRET_KEY=your-secret-key
DEBUG=False
Best Practices
- Separate development, staging, and production settings using environment variables or multiple settings files.
- Document all required environment variables for new team members.
- Use default values for non-sensitive settings to avoid runtime errors.
- Regularly review and update configuration for security and maintainability.