Django Settings File Tricks (Posted on March 9th, 2013)

Here are two really awesome tricks that have helped me with keeping my code sane on development and production.

Environment Variables

Environment variables are just like they sound. They are variables local to an environment such as development and production. You can basically store variables on the system so that when Django starts up it can use a certain variable value from development and a different one from the production server. We can set a DEBUG variable like so using a terminal window:

export DEBUG=

And we can read it like so:

import os
ENVIRONMENT = os.environ
DEBUG = bool(ENVIRONMENT.get('DEBUG', True))

We try and get the DEBUG variable from the system environment. If we can get one then we set our Django DEBUG setting to it. If we can't find one then we set it to True by default. So you can set your DEBUG value to False on production and then not set anything in your development environment for it to automatically be set to True. The cast to a bool is needed since the OS will store variable values as a string. Python treats empty strings as False which is why we don't assign a value to our DEBUG variable in the environment. If we wanted to set debug to True on the server then we could set our environment variable as such "export DEBUG=True".

File Path

It is often the case that where you store your files on your development machine is different from where you store your files on your production machine. So rather than storing two different file locations you can have Python get the file location for you.

SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

This will get the folder where your settings file is stored. You can then tell Django where your static files are stored by doing something like:

STATIC_ROOT = os.path.join(SITE_ROOT, 'static')

These two tricks have helped me in the past with going from development to production with ease. If you know any others post them in the comments below. Thanks for reading!

Tags: Django