Thursday, August 23rd, 2012

A Django filter to be more DRY

In Django one repetitive task which is done in your templates over and over again is normally the following:

<a href="{{object.get_absolute_url}}">{{object}}</a>

With my new template filter, which I believe should be in Django by default, will allow something DRY like this:


Isn't that so much easier than typing in the entire A tag for each link you want to place to an object in your code? The best part, is that this will work on ForeignKeys as well.


First, you will need to choose an app which will contain this template filter, inside the app create a new directory called templatetags, and inside that create a to turn it into a new Python package. Next create a new Python file, name it something you will use to load it into your templates. In this file enter in the following code:

from django import template
from django.template.defaultfilters import escape
from django.utils.safestring import mark_safe

register = template.Library()

def link(value):
    return mark_safe('<a href="%s">%s</a>' % (escape(value.get_absolute_url()), escape(value)))

There you have it, now you can easily link to objects from within your template, and still be DRY. Enjoy!

Python Powered | © 2012-2014 Kevin Veroneau