Reading
Configuring Django Settings
Issues:
- Environments - each differing environment may have its own settings and needs to be managed
- Sharing settings - one member may add an API and forget to add specific settings, causing problems
- Django settings = Python Code -may produce tricky logic
Setting Config Recommendations
settings_local.py
Used to extend environment-specific settings which will be ignored by version control. For example:
settings_local.py
ALLOWED_HOSTS = ['example.com']
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'production_db',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'db.example.com',
'PORT': '5432',
'OPTIONS': {
'sslmode': 'require'
}
}
}
...
from .settings_local import *
Settings files for each Environment
Keeps all configs in version control which can be shared between devs. All environments are included in version control. Still need to handle secret passwords and tokens.
settings/
├── __init__.py
├── base.py
├── ci.py
├── local.py
├── staging.py
├── production.py
└── qa.py
Running a project with a specific config requres an additional parameter:
python manage.py runserver --settings=settings.local
### Environment Variables/ django-environ
Better than using os.environ
.
```import environ
root = environ.Path(file) - 3 # get root of the project env = environ.Env() environ.Env.read_env() # reading .env file
SITE_ROOT = root()
DEBUG = env.bool(‘DEBUG’, default=False) TEMPLATE_DEBUG = DEBUG
DATABASES = {‘default’: env.db(‘DATABASE_URL’)}
public_root = root.path(‘public/’) MEDIA_ROOT = public_root(‘media’) MEDIA_URL = env.str(‘MEDIA_URL’, default=’media/’) STATIC_ROOT = public_root(‘static’) STATIC_URL = env.str(‘STATIC_URL’, default=’static/’)
SECRET_KEY = env.str(‘SECRET_KEY’)
CACHES = {‘default’: env.cache(‘REDIS_CACHE_URL’)}
### Structure
```project/
├── apps/
├── settings/
│ ├── __init__.py
│ ├── djano.py
│ ├── project.py
│ └── third_party.py
└── manage.py
Source:https://djangostars.com/blog/configuring-django-settings-best-practices/