Simple Django View For Dynamic Text Replacement

I just discovered this and though I like the idea, I don’t use PHP. However, the same thing could be done with Django, and the Python Imaging Library.

Please note that, this is tested, but in no way optimal, and will remain that way until I get time to do it right, or someone else does it right, or already has done it right….

First things first:

Define some aliases for fonts in


   'a': '/path/to/some/truetypefont.ttf',


Then, we define a url in

# other views here

(r'^(?P<fontalias>.*)/$', 'testtest.many.views.view_header'),

Then, we create the view… in this case view_header. This is the part that needs fixing.

from django.http import HttpResponse

from testtest import settings

import Image, ImageFont, ImageDraw

def view_header(request, fontalias):


        fontfile = settings.DYNAMIC_FONT_ALIASES[fontalias]


        return HttpResponse("not supported")

    if request.GET.has_key('text'):

        header = request.GET['text']


        header = 'Hello world'

    imf = ImageFont.truetype(fontfile, 20)

    size = imf.getsize(header)

    im ="RGB", size)

    draw = ImageDraw.Draw(im)

    draw.text((0, 0), header, font=imf)

    # anyone know a better way than saving first? I guess we get built in

cache this way…."/tmp/aaaa", "PNG")

    a = open("/tmp/aaaa", "rb")

    return HttpResponse(, mimetype="image/png")

And there you have it. Start up your application and point yourself to here, and marvel at the glory that is, Django dynamic headers… or what could be used as dynamic headers with some css.


— 2006-06-30