Monday, 30 July 2012

A Django Template Filter for UK Postcodes

I recently launched a new property portal, www.propertysquirrel.com

One of the things that cropped up whilst cleansing the property data was the need to capitalize postcodes, and add a space if it was missing.

For example, with flats to rent in Edinburgh, I'd often have an address like the following:

Craigend Park, Edinburgh, eh165xx,

I wanted to clean up the postcode, and display it as:

 Craigend Park, Edinburgh, EH16 5XX.

There are various ways to solve this. Writing a method on my model is one solution. Another that works surprisingly well is a nice little template filter.

import re
from django import template

register = template.Library()

def cleanup_postcode(match):
    upper = match.group(1).upper()
    if upper[-4] != " ":
        upper = upper[:-3] + " " + upper [-3:]
    return upper

@register.filter
def postcode(value):
    """Uppercase a postcode and insert a space if missing"""
    postcode = re.compile(r'([A-Z]{1,2}[0-9R][0-9A-Z]? ?[0-9][A-Z]{2})', re.IGNORECASE)
    return postcode.sub(cleanup_postcode, value)

To use it you can simply do the following (assuming this code is in a module called postcodes):

{% load postcodes %}
{{ address|postcode }}

This was pretty handy as it leaves the rest of the address untouched, which is exactly what I was looking for. If there's no postcode in the address, there's no problem.