Custom filters

On occasions, Django built-in filters fall short in terms of the logic or output they offer. In these circumstances, the solution is to write a custom filter to achieve the outcome you require.

The logic behind Django filters is entirely written in Python, so whatever is achievable with Python & Django (e.g. perform a database query, use a third party REST service) can be integrated as part of the logic or output generated by a custom filter.

Structure

The simplest custom Django filter only requires you to create a standard Python method and decorate it with @register.filter() as illustrated in Listing 3-23.

Listing 3-23 Django custom filter with no arguments

from django import template

register = template.Library()

@register.filter()
def boldcoffee(value):
    '''Returns input wrapped in HTML  tags'''
    return '<b>%s</b>' % value