Thursday, August 27, 2009

Automatic Django Template Directory adjustment

Django is that hot new MVC framework on the block that's kept me sleeping at night, quite unlike PHP. Yup, its that good! :) It's got wonderful features that make me feel - Yeah! Development for the web is still worth the grind! By the way, if you're not into Web Development and don't care two hoots about the difference between a framework and a library, this post is not for you - Mosey along now! Nothing to see here. ;)

Anyway, one of my few n00b questions to which I've never actually got a satisfactory answer is - How do you specify the template directory so that you can send your code to others and have it execute by runserver without any changes? The primary problem is the hardcoding of directories that is done in the file at the root of the project. After a bit of searching, I've come to a satisfactory solution and lest I forget it, I've decided to post it to my blog. Here's the code snippet.

# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
# os.path.realpath(os.path.curdir).replace("\\", "/") + "/templates",
os.path.abspath(os.path.dirname(__file__)).replace("\\", "/") + "/templates"

This seems to work most of the time, just let me know how it works out for you!