Django Standalone Templates

Motivation

At work, I needed to include a set of simple information in a web page. All I needed to do was include about four calculated values in a table. I didn't want to do a full-blown django installation for such a simple task. I decided that since PHP was originally designed to be able to insert things into straight html, that it might be a good choice for the task. I spent twenty minutes with it, and I was fed up.

I needed to use python. I first thought back to my PERL days when I would have it spit out all the html for a page through print statements. It was ugly then, and is still ugly. I realized that the django template language would be ideal, but I still didn't want to have a full-blown django installation.

Implementation

It was much easier to implement than I first suspected. I created a script that calculated the variables, imported django's template system, and rendered the template with the calculated variables.

Here is the general idea:

from django.template import Template, loader, Context

c = Context({"value1": 0.1234})
t = loader.get_template(template_name="index.html")
print t.render(c)

The only requirement is that DJANGO_SETTINGS_MODULE is set. My settings module for this simple script has only one value: TEMPLATE_DIRS.

This script alone isn't enough to actually get it to work, I have to output headers as well. The easy fix is to have a print line that takes care of that:

print "Content-type: text/html\n\n"

I also have to make the script executable, and add a shebang line:

#!/usr/bin/python

Eureka! I have created a simple cgi script that utilizes the django template engine.