Django, virtualenvwrapper and multiple settings files
Finally figured out something really annoying.
Two Scoops of Django: Best Practices for Django 1.5 advocates what is essentially Jacob Kaplan-Moss’s The One True Way proposal from his talk ‘The Best (and Worst) of Django’ (slides 50 to 52).
So I had a go at implementing The One True Way by creating a settings directory in the project package directory and converting my settings.py
and settings_local.py
into base.py
, local.py
, production.py
etc.
I then tried to run django-admin.py runserver --settings=project.settings.local
and got this error message:
ImportError: Could not import settings 'project.settings.local'
(Is it on sys.path?): No module named project.settings.local
So yes: the parent directory of project
(my project package) needed to be added to sys.path. The question was how to do this in a non-messy way using virtualenvwrapper.
Turns out the solution was proposed back in March 2008 by none other than James Bennett (as described by this Stack Overflow post): use virtualenvwrapper’s add2virtualenv
command to add the specified directory to the virtualenv’s PYTHONPATH
.
So I did this for project‘s parent directory:
add2virtualenv /path/to/parent/directory
To prove it worked:
python -c "import sys; print sys.path"
['', '/path/to/parent/directory', ...]
It goes away when you deactivate your virtualenv and comes back when you activate it again. Perfect.