Django offers a lot of template filters out of the box but in a few cases, you would have to create yours. In this post, I will be showing you how to create custom template filters in Django to match your specific business logic.

 

Before creating a template filter or tags, you should first create a directory named templatetags inside an app (same level with models.py, views.py files) that has been added to the INSTALLED_APPS.

 

Inside the directory, create an empty __init__.py file to tell python to treat the directory as a package and all its py files as a module. Then, you could create a new python file that would contain the custom filters and tags; let's call it anyname.py.

 

exampleapp/
    __init__.py
    models.py
    templatetags/
        __init__.py
        anyname.py
    views.py

 

For the custom filter created to be valid, the anyname.py file must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered.

 

from django import template

register = template.Library()

 

Secondly, you must load the filters and tags created into the templates where you would like them to be used by adding:

 

{% load anyname %}

 

Creating Custom Template Filters In Django.

A filter is a function used in the template to modify values by manipulating the value itself or by taking a second argument which will be used to manipulate the main value.

 

Filters are used by adding a pipe( | ) then the filter and finally the second argument if any.

 

{{ somevariable|filter:optional_argument }}

 

Let's create a simple filter that converts to a list.

 

from django import template

register = template.Library()

@register.filter(name='string_to_list_filter') 
def string_to_list(string):
    """
    Returns a list from strings from a sentence
    
    """
    return string.split()

 

By default, a filter takes two arguments: a value which is the value that the filter will be acting upon and an optional second argument.

 

Also, your filter must be registered using the register.filter method as shown above.

 

{{ "Hello world" |string_to_list_filter}}

 

Notice that the filter is called in the template with the value passed to the name above in the filter method. Also, the name attribute takes the function name by default if a name is not given.

Conclusion

Django has provided a lot of in-built filters so check out the documentation before deciding to create yours because there is a high probability that the filter you are about to create is already available.

 

For more info check out the documentation on this.

 

Follow me on Twitter for more amazing content.

 

Keep coding. Keep learning. God bless you.

 

This was originally published on codingwithease.com