pymarco
pymarco

Reputation: 8195

Django - referencing different settings files from wsgi depending on server

I'm surprised I can't find an existing question related to this. Perhaps there's an obvious answer that I'm overlooking. But, let's say I have my django project named "foo". Settings for foo are defined in multiple files as encouraged by the Two Scoops book.

settings/
    local.py
    dev.py
    prod.py

Dev and prod are separate instances of the same repo both of which are served using Apache through my Webfaction account. For the dev site I want it to use settings/dev.py and for the prod site I want it to use settings/prod.py. My wsgi.py file contains the following line:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.settings.prod")

This is where I get confused. How to load the dev site with foo.settings.dev instead?

Could I replace wsgi.py with multiple files, and then in each of my httpd.conf files assign WSGIScriptAlias to the correct wsgi file?

wsgi/
    dev.py
    prod.py

Thanks

Upvotes: 7

Views: 2318

Answers (3)

Q Caron
Q Caron

Reputation: 1043

What you can do is use the name of the settings that should be picked in the path to your wsgi file. Say the path to your wsgi is /www/production/django_project_name/wsgi.py, then you could do the following in that file:

import os
import re

match = re.match('/www/(\w+)/.+', os.path.realpath(__file__))
environment = match.group(1)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings." + environment)

Upvotes: 0

Graham Dumpleton
Graham Dumpleton

Reputation: 58543

Another way to do it is have each site running in a different mod_wsgi daemon process group. Name these daemon process groups as 'local', 'dev' and 'prod'.

In your WSGI script file you could then use:

import mod_wsgi
os.environ['DJANGO_SETTINGS_MODULE'] = 'foo.settings.%s' % mod_wsgi.process_group

In other words, use the name of the mod_wsgi daemon process group to dynamically select the configuration.

Upvotes: 7

Serafeim
Serafeim

Reputation: 15094

If I recall correctly, the two scoops book proposes using environment variables to set various settings - one of these should be the location of the django settings module.

So just try setting and environment variable DJANGO_SETTINGS_MODULE equal to "foo.settings.dev" in your development system and "foo.settings.prod" in your production.

The setdefaul just sets the DJANGO_SETTINGS_MODULE to a default in case you haven't defined it yourself - you may comment it out or just ignore it.

Upvotes: 1

Related Questions