Custom Django filters in Google App Engine

You want to create your own custom Django filters in App Engine without running a whole Django stack? Here’s how in a few lines of code.

First create a specific python file to hold your custom filters at the root of your application. In my case I use customfilters.py like this:

import re
from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def escapeimg(body):
	return re.sub(r'

', '[IMG]', body)

register.filter(escapeimg)

Then in your main application source file, call the following line outside of the main() definition, for example just after your modules loading:

"""Load custom Django template filters"""
webapp.template.register_template_library('customfilters')

You should then be able to use the new filters you registered in customfilters.py straight away in any of your Django templates without any % load foobar % call

8 thoughts on “Custom Django filters in Google App Engine”

  1. I’ve just discovered custom filters thanks to this posts – and DAMN aren’t they powerful! Solved a bunch of stuff for me and made everything so small, neat and simple. Thank you HEAPS for this info.

  2. I tried the same thing. and it didn’t work. I received the following error:
    InvalidTemplateLibrary: Could not load template library from customfilters, No module named customfilters

Leave a Reply

Your email address will not be published. Required fields are marked *