Using Multiple Settings Files in Django
Instead of using a single settings.py file, we can create multiple settings files tailored for different environments (e.g., local development, production, staging, testing, etc.).
This approach allows us to manage configurations more effectively and adapt the project to specific needs.
To implement this, create a settings/ directory containing your settings files. The directory structure will look like this:
settings/
├── init.py
├── base.py
├── local.py
├── staging.py
├── production.py
├── test.py
base.py: This file contains the generic settings that are common across all environments. it is the foundation for your settings.
# settings/base.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'your-secret-key'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add your apps here
]
In local.py, you override or add settings specific to local development:
# settings/local.py
from .base import *
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'twoscoops',
'HOST': 'localhost',
}
}
INSTALLED_APPS += ['debug_toolbar']
Running the Project:
To use the local.py settings, run the Django development server with the --settings flag:
python manage.py runserver --settings=settings.local
Benefits:
Better organization: Keeps settings modular and easier to maintain.
Improved security: Sensitive production settings (e.g., secret keys, database credentials) can be isolated from development settings.