Previous Page Next Page

Creating Custom Filters

Creating custom filters is easy. Filters are really just Python functions that accept either one or two arguments. The first argument is the value to which the filter will be applied. The second argument is the filter argument, if any, that is attached to the filter in the template.

For example, consider the following template code:

{{ "1.2.3.4"|drop:"." }}

The arguments value and arg in the following filter function would be set to 1.2.3.4 and . respectively:

def drop(value, arg):
  return value.replace(arg, '')

After you have created the filter function, you need to register it with the Library object in the module. To register a filter with a Library object, you call the filter() function of the Library object and pass in the filter name as the first parameter and the filter function as the second:

from django import template
register = template.Library()

def drop(value, arg):
  return value.replace(arg, '')
register.filter('drop', drop)

Did you Know?

If you are using Python 2.4 or later, you can register the filter using a decorator function. If you do not pass a name argument to the decorator function, the filter function name is used as the filter name. For example, in the following two decorator statements, the name of the filter is DropChar in the first decorator and drop in the second:

@register.filter(name="DropChar")
def drop(value, arg):
. . .
@register.filter()
def drop(value, arg):


Did you Know?

If your filter is expecting a string, you can use the @stringfilter decorator for the filter function. The @stringfilter decorator converts objects to their string values before passing them to the filter function. The following code snippet shows an example of using the @stringfilter decorator:

@register.filter(name=" FilterText")
@stringfilter
def FilterText(value, arg):


Try It Yourself: Create a Custom Template Filter

In this section, you will create a custom template filter to display datetime objects in a specific format without having to use the date filter and filter string. This type of filter can save you keystrokes and time if you have a set way you want datetime objects to be displayed.

Follow these steps to create a custom filter module and add the time filter to it:

1.
Create and open a file called iFriends/Custom/templatetags/custom_filters.py.

2.
Add the following lines of code, shown in Listing 13.1, to import the django.template package and create a Library object so that Django recognizes the module as a valid filter library:

from django import template
register = template.Library()

3.
Add the following lines of code, shown in Listing 13.1, to import the datetime and create a filter function longTime that accepts a datetime object and returns it as a specific string format:

import datetime
. . .
def longTime(aTime):
    return aTime.strftime("%m/%d/%Y %I:%M%p")

4.
Add the following line of code to register the filter with the Library object for the module:

@register.filter(name="longTime")

Watch Out!

If you are using Python 2.3 or earlier, you must use the following line of code after the function to register it with the library:

register.filter('drop', drop)

5.
Save the iFriends/Custom/templatetags/custom_filters.py file.

6.
Open the iFriends/templates/Blogs/blog_details.html file in an editor.

7.
Add the following line of code, shown in Listing 13.2, to load the custom_filters.py library module you created in step 1:

{% load custom_filters %}

8.
Modify the following line of code to use the longTime filter to display the blog.date field:

<font size="2">{{ blog.date|longTime }}</font>

9.
Save the iFriends/templates/Blogs/blog_details.html file.

10.
Open the following URL in a web browser to bring up the blog_details generic view, shown in Figure 13.1, to verify that the date is formatted correctly:

http://127.0.0.1:8000/generic/blog_details/1/

Figure 13.1. The blog_details generic view showing the date and time formatted using the longTime custom filter.


Listing 13.1. Full Contents of iFriends/Custom/templatetags/custom_filters.py

from django import template
register = template.Library()
import datetime

@register.filter(name="longTime")
def longTime(aTime):
    return aTime.strftime("%m/%d/%Y %I:%M%p")

Listing 13.2. Full Contents of iFriends/templates/Blogs/blog_details.html

{% extends "iFriends_base.html" %}

{% block title %}Generic Blog Details{% endblock %}
{% block content %}
{% load custom_filters %}
<table width="400">
<tr bgcolor="aabbcc"><td colspan="3">
<font size="5" color="white">{{ blog.title }}</font>
<font size="2">{{ blog.date|longTime }}</font>
</td></tr>
<tr valign="top"><td bgcolor="ddffff">
{{ blog.text|linebreaks }}
</td></tr>
{% endblock %}


Previous Page Next Page