-multi environment- Django settings
Love Django, at least at the time of writing this blog.
One of the issues I had to overcome before really enjoying deploying Django was setting a proper multi environment settings system.
I always work within Virtual Environments using pyvenv, and also I always have My Django (and python) dev env properly setup.
Create Django project
cd /path/to/project pyvenv venv source venv/bin/activate django-admin startproject PROJECT
Set multi-environment settings
The idea is to have different settings for different environments (dev, testing, production, whatever-else-suits-you, ...) which are part of your VCS repo. Which all load some base settings. Which can then be overridden. I usually have at least 3 files on a very basic project:
|- project |- ... |- manage.py |- your-django-app |- ... |- settings.py |- config <--- (this is new) |- base.py <--- (all the common settings) |- development.py |- production.py
You can get the example files from my config_files repo.
- Place the files as shown above
- Replace PROJECT in settings.py with your app name
- Adjust settings files to suit your needs
- Set an environmental variable ENVIRONMENT with the name of the desired settings to be loaded
Run your django server (in case of Dev environment)
Load settings from environmental variables
I like the idea of having even the development settings file revisioned, and have all critical values (API keys, passwords, ...) loaded from environmental variables. Doing so in any Python project is easy with Virtual Environments. All you need to do is use your own activate file from which you source the original. I usually place the file at the same level as the venv folder.
|- /path/to/project |- activate <--- Your own personal activator |- venv |- ... |- bin |- ... |- activate <--- Original |- project |- ...
Once the file is in place all you have to do is:
cd /path/to/project source activate
It can only get a bit confusing if you don't document all the variables you need to set, for your app to work properly. I have a very simple way of keeping track of all the variables I need: add them at the beginning of the base.py settings file to a dictionary, and only use them from the dictionary itself. That way all I need to do is open my base.py file and there they are.