Django dynamic template paths

Several add-on applications for Django bring in their own templates and expect user to hardcopy those files into project’s template directory. The problem raises when add-on egg is updated and its hardcopied templates are not. Another approach could be to add add-on template directory path to TEMPLATE_DIRS variable in project’s settings.py. However, once add-on application is updated, hardcoded path may not be up-to-date.

UPDATE: Vinicius Mendes commented on using django.template.loaders.app_directories.Loader to solve the problem (a similar module exists for eggs, which is named django.template.loaders.eggs.Loader). It’s definitely the easiest way if you don’t mind importing all of your applications templates. Instead, if you need to pick only selected directories or non-standard directory names, keep on reading.

The solution is to add a dynamic path that is resolved at runtime using add-on egg’s path. Here’s an example of how I got django-reversion templates added:

import os
from  pyclbr import readmodule_ex

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), "../templates"),
    os.path.join(os.path.dirname(readmodule_ex('reversion')['__path__'][0]), "templates"),
)
This entry was posted in Coding, How-tos and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted January 25, 2010 at 1:33 PM | Permalink

    Django has a template loader that solves this problem. Take a look at the django.template.loaders.app_directories.Loader [1]

    [1] http://docs.djangoproject.com/en/dev/ref/templa…

  2. Posted January 25, 2010 at 2:39 PM | Permalink

    True, but django.template.loaders.app_directories.Loader and django.template.loaders.eggs.Loader are an all-or-nothing solution.

One Trackback

  1. [...] This post was mentioned on Twitter by Planet Python and PlanetDjango.org, Geek Scrap. Geek Scrap said: Django dynamic template paths http://goo.gl/fb/QUtE #coding #howtos #django #pyclbr #python #readmoduleex #reversion [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>