Reputation: 210
After looking around I have come up with the following code this seems to work well I was wondering what others have come up with and feedback would be great.
settings/init.py
import sys
import socket
# try to import settings file based on machine name.
try:
settings = sys.modules[__name__]
host_settings_module_name = '%s' % (socket.gethostname().replace('.', '_'))
host_settings = __import__(host_settings_module_name, globals(), locals(), ['*'], -1)
# Merge imported settings over django settings
for key in host_settings.__dict__.keys():
if key.startswith('_'): continue #skip privates and __internals__
settings.__dict__[key] = host_settings.__dict__[key]
except Exception, e:
print e
from settings.site import *
settings/base.py
BASE = 1
SITE = 1
LOCAL = 1
settings/site.py //project specific
from settings.base import *
SITE = 2
LOCAL = 2
settings/machine_name_local.py //machine specific settings for developers or host server
from settings.site import *
LOCAL = 3
Upvotes: 1
Views: 407
Reputation: 1638
I think that while your code probably works, it's unnecessarily complicated. Complicated code is rarely a good thing because it's hard to debug, and your settings module in the last place you want to introduce errors in your Django project.
It's easier to have a settings.py
file, with all settings for the production server plus settings common to all development machines and have a local_settings.py
imported at the bottom of it. The local_settings.py
would then be where the developers add settings specific to their machines.
settings.py:
# all settings for the production server,
# and settings common to all development machines eg.
# INSTALLED_APPS, TEMPLATE_DIRS, MIDDLEWARE_CLASSES etc.
# Import local_settings at the very bottom of the file
# Use try|except block since we won't have this on the production server,
# only on dev machines
try:
from local_settings import *
except ImportError:
pass
local_settings.py
# settings specific to the dev machine
# eg DATABASES, MEDIA_ROOT, etc
# You can completely override settings in settings.py
# or even modify them eg:
from settings import INSTALLED_APPS, MIDDLEWARE_CLASSES # Due to how python imports work, this won't cause a circular import error
INSTALLED_APPS += ("debug_toolbar",)
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
Just remember not to upload the local_settings.py
on the production server, and if you are using a VCS, to configure it such that the local_settings.py
file is ignored.
Upvotes: 4