Vinyll's blog

( Python, Javascript & Web stuff… )

Managing configuration files with Django

The trick here will be to keep the settings.py file containing all default values. Then, we'll create one file per environment that will get the settings.py values, and might override them, or add new (could even delete I guess). As we'll have multiple config files, we'll package them:

Configuration tree structure

/project/conf
    /__init__.py
    /settings.py
    /local.py
    /staging.py
    /prod.py

Configuration file content

Your settings.py file will keep the default and customized values as usual. Other 3 files will have same content as below (all 3 similar).

Example with file "local.py"

from conf.settings import *

    DEBUG = True
    TEMPLATE_DEBUG = DEBUG
    OTHER_VAR = "value in local"

Update manage.py and wsgi.py

You should update these 2 files accordingly. manage.py will obviously refer to local.py :

manage.py

Point your DJANGO_SETTINGS_MODULE to conf.local :

#!/usr/bin/env python
import os
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.local")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

wsgi.py

Set DJANGO_SETTINGS_MODULE to conf.staging or conf.prod depending on wich environment will call it :

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.staging")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Extra tips

Yes, that's all working already !

Install apps in local only

Some apps such as django-debug-toolbar should be installed and configured in local environment only. Here's how :

/project/conf/local.py : INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)

Manage urls the same way

In most Django code you can read at the bottom of urls.py file something like :

Tricky usual code

if settings.DEBUG is True:
    urlpatterns += patterns('',
        (r"^static/(?P<path>.*)/?$", 'some.static.views')
    )

That's great, that doesn't load that url if we did not activate DEBUG. But that's really tricky !

Clean way

In /projects/conf/local.py, add :

…
ROOT_URLCONF = 'app.urls_local'

And create a app/urls_local.py (or path accordingly), containing :

from urls import *
    urlpatterns += patterns('',
        (r"^static/(?P<path>.*)/?$", 'some.static.views')
    )

(change "from urls …" accordingly to whatever package matches your urls.py file).

By vinyll on Jan. 16, 2012


Comments