We have already discussed Django Template Tags. In this tutorial, we will work with Django Custom Template Filter.

What is a Template Filter in Django?

A template filter is simply a feature that can transform the value of a template variable before it is displayed.

Syntax

{{ variable_name | filter_name }}

Built-In Django Template Filters

There are some inbuilt filters in Django. Let’s see some of them first.

lower

To convert the value of a variable into lower case characters:

{{ variable | lower }}

If value is “Bangladesh”, the output will be “bangladesh”.

upper

To convert the value of a variable into uppercase characters:

{{ variable | upper }}

If value is “Bangladesh”, the output will be “BANGLADESH”.

truncatewords

The filter below is used to cut the value of the variable if its length exceeds 3 words. Here ‘3’ is an argument.

{{ variable | truncatewords:"3" }}

If value is “Bangladesh is beautiful country”, the output will be “Bangladesh is beautiful”.

Till now we were using only one filter but we can chain as many filters as we want.

{{ variable| upper | truncatewords:"30" }}

More Built-In Template Filters of Django

add addslashes capfirst
center cut date
default dictsort divisibleby
escape filesizeformat first
join last length
linenumbers lower make_list
random slice slugify
time timesince title
unordered_list upper wordcount

Custom Filters

Custom filters are simply Python functions that take one or two arguments.

  • The value of the variable (input) – not necessarily a string.
  • The value of the argument – this can have a default value, or be left out altogether.

Creating Custom Filters

We wil create a folder named ‘templatetags’ inside our app & then create an empty __inti__.py file inside it. Let’s create a python file named new_template_tags.py where we will write our filters.

Before creating our template filter let’s look into our Model. We will work with this model.

Model
class Person(models.Model):
    GENDER = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(unique = True,null=True)
    gender = models.CharField(max_length=6, choices= GENDER,default='N/A')

We have created 6 objects of this model in our database. We will show all of them in our template. If gender is ‘Male’ we will represent it as ‘Boy’ & if gender is ‘Female’ we will show ‘Girl’ in the template. So, to manipulate this inside our template we will use template filters. We can do it in our views too but using template filters is recommended. Everything is set. Let’s create our first filter.

def custom_filter(value):
    if value=='Female':
        return "Girl"
    elif value == 'Male' :
        return "Boy"
    else:
        return "Unknown"

This is a very simple function that will return a value based on the input. Now we will have to register this function in template library to make it accessible to Django’s template language.

Registering custom filters

There are two ways of registering template filters. One is using a decorator:

from django import template
register = template.Library()

@register.filter(name='filtername')

This line should be written just before the filter definition.

We can register filter also like this Example

register.filter('filtername', filtername)

We will use first method here.

from django import template

register = template.Library()

@register.filter(name='custom_filter') 
def custom_filter(value): 
    if value=='Female': 
        return "Girl" 
    elif value == 'Male' : 
        return "Boy" 
    else: 
        return "Unknown"
Template

We will have to load our template filters in our template. The syntax is:

{% load new_template_tags %}

{% load new_template_tags %}

{% for person in persons %}
<a href="{% url 'person-detail-view' person.id %}">
    <h3>{{person.first_name  }} {{person.last_name  }}</h3>
</a>
<h4>Gender: {{ person.gender | custom_filter }}</h4>

{% endfor %}

Output:

Using In CSS

We can also manipulate our CSS using template filters. We will use the previous example, but now we will use a filter in styling our tags. If gender is ‘Female’ then the color will be ‘red’ and if gender is ‘Male’ the color of the element will be ‘green’ otherwise ‘yellow’.

@register.filter(name='color')
def get_color(value):

    if value=='Female':
        return "red"
    elif value == 'Male' :
        return "green"
    else:
        return "yellow"
Template
{% load new_template_tags %}

{% for person in persons %}
<a href="{% url 'person-detail-view' person.id %}">
    <h3>{{person.first_name  }} {{person.last_name  }}</h3>
</a>
<h4 style="color:{{ person.gender | color }};">Gender: {{ person.gender }}</h4>
{% endfor %}

Output:

I hope, it was a helpful tutorial for you. Now, try to implement your own template filters. Best of luck.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)