October 3, 2008
Two simple techniques to make your Django projects ultra portable
After moving around my Django projects between Windows and Linux boxes and different mySQL setups I spent some time looking for the best solution on making my project portable so I can throw it around wherever I want without much worry. Both these solutions are some-what known as I got them from the #django irc room (a super awesome resource!) but not much documentation is out on them.
1) Setting a ROOT_DIR and using it in settings.py
This is very simple. You want to setup a ROOT_DIR variable that basically consists of Python code that figures out what directory the file is in. The code is very simple:
import osROOT_DIR = os.path.dirname(__file__) Place this on top of your projects settings.py and then include it in the various variables later in the file, like TEMPLATE_DIRS will have an entry ROOT_DIR + ‘/templates’ or you can drop the hard-coded ‘/’ and do something like os.path.join(ROOT_DIR, ‘templates’) which takes out a tiny worry of including, or not including a slash in your paths. (Thanks to SmileyChris in the comments for optimizing my implementation on this, as well as adding an additional tip .. check below for it!)
2) Using a local_settings.py for easy moving around between environments
Another very simple but super useful trick. This allows you to over-ride any variables in settings.py for that specific machine. A simple use case for this would be that I have my development environment here on my Ubuntu machine but when I commit my project to SVN on the Debian server the mySQL details are different as it’s an entirely different server. So what I do is at the bottom of settings.py:
try:from local_settings import *
except ImportError, exp:
pass # You can do something here, like write to a log if you wish, but it’s not necessary
Then, setup settings.py so it matches your production environments settings (In this case, my Debian server) and create a new file called local_settings.py in the same directory. In this file, you can just place whatever vairables you want to over-ride. I have variables over-riding my MySQL and DEBUG settings to fit my local development (Ubuntu) environment. The key here is to not commit/send local_settings.py to production.
And that’s about it. Those two small changes make it very easy for my projects to move around. It makes it very nice to be able to commit even settings.py to your production environment and not worry about values not being correct.
If you know of any other good portability techniques I’d be glad to hear them in the comments section below, I’m still learning Django!
Hi! I'm Bart, Currently enjoying life in Waterloo, Ontario. I love Programming, Cooking, Music, Science ... and pretty much everything interests me.