Aug 9, 2015

-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
   |- ...
   |- your-django-app
      |- ...
      |- config <--- (this is new)
         |- <--- (all the common settings)

You can get the example files from my config_files repo.

  1. Place the files as shown above
  2. Replace PROJECT in with your app name
  3. Adjust settings files to suit your needs
  4. Set an environmental variable ENVIRONMENT with the name of the desired settings to be loaded
  5. Run your django server (in case of Dev environment)

    ./ runserver

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

Get example activate file.

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 settings file to a dictionary, and only use them from the dictionary itself. That way all I need to do is open my file and there they are.