Toast Driven

← Back to January 4, 2010

Better Local Settings

A common convention I've seen in the Django community is to place code like the following at the bottom of your settings file:


# ``settings.py``
# Lots of typical settings here.
# ... then ...

try:
    from local_settings import *
except ImportError:
    pass

Then storing machine/user-specific settings within a local_settings.py> file. This file is set to be ignored by version control.

I can't argue with needing overridden settings (do it all the time) but that import is backward in my opinion. My preferred technique is to still use the settings.py and local_settings.py but relocate the import. So local_settings.py starts out with:


# ``local_settings.py``
from settings import * # Properly namespaced as needed.

# Custom settings go here.
DATABASE_HOST = 'localhost'

The only other change is passing --settings=local_settings to any ./manage.py or django-admin.py calls.

Trivial implementation, you still only need to override what you need, no changes needed to version control or development workflow. And since you've already imported all of the base settings, you can reuse that information to create new settings, like:


# ``local_settings.py``
from settings import *

DATABASE_NAME = "%s_dev" % DATABASE_NAME

This is by no means a new technique, nor did I come up with it, but it's been very useful to me and I have yet to encounter the drawbacks (other than specifying the --settings flag, which also has an even easier fix via DJANGO_SETTINGS_MODULE) of this approach.

Feedback, as always, is welcome.

Toast Driven