[Fixed]-Managing multiple settings.py files

30👍

I use a settings module that is not a single file:

settings/
    __init__.py
    _base.py
    _servers.py
    development.py
    production.py
    testing.py

The __init__.py file is simple:

from _servers import get_server_type
exec("from %s import *" % get_server_type())

The _base.py file contains all of the common settings across all server types.

The _servers.py file contains a function get_server_type() that uses socket.gethostname() to determine what type of server the current machine is: it returns development, production or testing.

Then the other files look a bit like (production.py):

DEBUG=False
TEMPLATE_DEBUG=False
from _base import *

In each of these files, I put in the settings that only apply to this server type.

9👍

The trick that seems to be the most common is to maintain both a settings.py and local_settings.py (one for each environment) file.

Environment agnostic settings go into settings.py and at the bottom of the file, you’ll import from local_settings.py

try:
    from local_settings import *
except ImportError:
    pass

You can override any settings.py settings in the appropriate local_settings.py

7👍

django-admin.py / manage.py both accept a --settings=mysite.settings option. In development you could explicitly specify --settings=dev_settings. You can also set the DJANGO_SETTINGS_MODULE environment variable in your apache configuration.

Personally, I simply don’t check in settings.py. Instead I check in multiple settings files (dev_settings, prod_settings, etc) and symbolically link them to settings.py as desired. This way if I simply checkout my application it won’t be runnable until I think about which settings file is appropriate and actually put that settings file in place.

Another suggestion I’ve heard but I don’t particularly like is having a settings.py that dynamically imports a dev_settings.py if it exists. While this may be more convenient I’d be concerned that it’s harder to read settings.py and know what the settings will actually be without also looking for overriding values in a dev_settings.py file that may or may not exist.

👤stderr

2👍

My preferred way is to load a separate ini file using ConfigParser, based off a single setting or environment variable. Anyway in the django wiki there are many different options described: http://code.djangoproject.com/wiki/SplitSettings

Leave a comment