Two Scoops of Django: Best Practices for Django 1.5 suggests using version control for your settings files and storing the files in a separate directory:
project/
app1/
app2/
project/
__init__.py
settings/
__init__.py
base.py
local.py
production.py
manage.py
The base.py
file contains common settings (such as MEDIA_ROOT or ADMIN), while local.py
and production.py
have site-specific settings:
In the base file settings/base.py
:
INSTALLED_APPS = (
# common apps...
)
In the local development settings file settings/local.py
:
from project.settings.base import *
DEBUG = True
INSTALLED_APPS += (
'debug_toolbar', # and other apps for local development
)
In the file production settings file settings/production.py
:
from project.settings.base import *
DEBUG = False
INSTALLED_APPS += (
# other apps for production site
)
Then when you run django, you add the --settings
option:
# Running django for local development
$ ./manage.py runserver 0:8000 --settings=project.settings.local
# Running django shell on the production site
$ ./manage.py shell --settings=project.settings.production
The authors of the book have also put up a sample project layout template on Github.
Best Answer
The
DJANGO_SETTINGS_MODULE
environment variable controls which settings file Django will load.You therefore create separate configuration files for your respective environments (note that they can of course both
import *
from a separate, "shared settings" file), and useDJANGO_SETTINGS_MODULE
to control which one to use.Here's how:
As noted in the Django documentation:
So, let's assume you created
myapp/production_settings.py
andmyapp/test_settings.py
in your source repository.In that case, you'd respectively set
DJANGO_SETTINGS_MODULE=myapp.production_settings
to use the former andDJANGO_SETTINGS_MODULE=myapp.test_settings
to use the latter.From here on out, the problem boils down to setting the
DJANGO_SETTINGS_MODULE
environment variable.Setting
DJANGO_SETTINGS_MODULE
using a script or a shellYou can then use a bootstrap script or a process manager to load the correct settings (by setting the environment), or just run it from your shell before starting Django:
export DJANGO_SETTINGS_MODULE=myapp.production_settings
.Note that you can run this export at any time from a shell — it does not need to live in your
.bashrc
or anything.Setting
DJANGO_SETTINGS_MODULE
using a Process ManagerIf you're not fond of writing a bootstrap script that sets the environment (and there are very good reasons to feel that way!), I would recommend using a process manager:
environment
configuration key..env
) file.Finally, note that you can take advantage of the
PYTHONPATH
variable to store the settings in a completely different location (e.g. on a production server, storing them in/etc/
). This allows for separating configuration from application files. You may or may not want that, it depends on how your app is structured.