Feed

unfoldthat.com

Organizing Django settings

I think it’s not cool that I’m not blogging. I decided to write small posts about several simple things, techniques and conventions I use often.

Configuration is hard to get right, and I don’t think Django’s settings is the best way to configure a web app. The most common problem with Django’s settings is a desire to customize them for some particular environments, e.g. have a different DATABASE setting on development and production machines. And on of the most common solutions is simple and stupid:

# settings.py as is, the standard Django's from django-admin.py startprojects

DEBUG = True

TEMPLATE_DEBUG = True

# ... all this kind of stuff, and in the end:

try:
    from local_settings import *   # this is wrong. don't do this!
except ImportError:
    pass

The main reason to hate it when somebody does it is that you can’t use any value from settings.py in local_settings.py. It’s not cool. I want to be able to do things like, you know:

INSTALLED_APPS += ('gunicorn',)

No, it’s not possible. And don’t try from settings import INSTALLED_APPS, it won’t work.

What to do about it?

I really think of myself as a smart person, but the first time I decided to solve this problem I failed horribly. I make settings.py import a function from local_settings, which will take locals() and modify them as it wishes. You don’t want to try.

According to PEP20,

There should be one– and preferably only one –obvious way to do it.

And it seems like yes, there is! So, here, the ultimate guide on how to make everyone able to override settings in their local environment while not being rude, bad or ugly:

mkdir settings

mv settings.py settings/base.py

wget https://gist.github.com/raw/947753/e7d3aa82de5a1ba82f9b5532ae2f4240dbbfd5c7/__init__.py -O settings/__init__.py

Please take a look at the gist from which __init__.py is downloaded. The __init__.py itself is very simple, and an example of local.py (optional) is there too.

Oh, one more thing about local.py:

echo "settings/local.py" >> .gitignore

A little more settings cuteness in the next blogpost.

Update, 2nd of May: As Josh Smeaton pointed out, there is another idea - to use a special settings file for every developer. He said that they use special settings, manage and even urls modules for everyone, and in my opinion there can be use-cases for this style of environment division.

29th of April, 2011

blog comments powered by Disqus

Please send your comments, ideas, rants and job offers at v.golev@gmail.com.

Made with Nginx, Jekyll, Git, EC2 and Emacs.

Regarding all the advertising and readability money-related stuff: I'm sorry. I'm really interested in whether one can make money by showing ads in his blog. Seems like I can't. If someone is really annoyed by adwords, drop me a line, I'll reconsider.

© Valya Golev, 2011