How to Create Custom Template Filters in Django?

How to Create Custom Template Filters in Django?

Django offers many inbuilt template filters to design the presentation layer. In Python, the filter is nothing but the function.

Sometimes, you don’t find the filter for the functionality you want to include. Just to give an example, Django does not have a template filter to divide numbers, unlike add.

Do you know you can also create custom template filters in Django?

In this tutorial, I’m going to demonstrate to you the steps to create custom template filters in Django.

Getting started

Before we start, hope you are familiar with the Django app.

First of all, create a new directory called templatetags inside the app directory. Create two files called __init__.py and custom_tags.py inside it.

Note: Adding __init__.py inside any directory, Python treats it as a module. Keep this file blank.

Here is the structure after creating templatetags module.

my_app/
├── __init__.py
├── admin.py
├── models.py
├── templatetags/
│   ├── __init__.py
│   └── custom_tags.py
└── views.py

Edit custom_tags.py file. Add below three lines of code into your file to start with creating a custom Django template filter.

from django import template
from django.utils import timezone

register = template.Library()

To use our custom filters in our template file (HTML file) you have to load it in the template. You can do that with a single line of code as…

{% load custom_tags %}

You have done with setting up the custom Django template filters. This is pretty simple, isn’t it?

Now let’s start creating one simple filter.

Custom Template Filters in Django

Let’s say, we want to create a filter called “divide” which is used to divide the template number object with a certain value.

Here we are defining a method called divide() with two parameters value and arg. It returns the value/arg.

After that, you have to register the filter to use it.

This is how your template filter looks like.

from django import template
from django.utils import timezone

register = template.Library()

def divide(value, arg):
	return value/arg

register.filter('days_from_current_date', days_from_current_date)

We can also pass multiple arguments to the filter.

Now, create one simple view.

def my_view(request):
    context = {
        "length_cm": 5000,
    }
    return render(request, "index.html", context)

Here we are passing context parameter length_cm to the HTML template index.html.

The usual syntax for template filter is {{ value|filter:arg }}.

We are going to edit the HTML template (index.html) to convert the centimeter length to the meter using our customized Django template filter.

{% load custom_tags %}

Length in meter: {{ length_cm | divide:100}}

Simply, we are dividing lenght_cm by 100 to convert it into meter length.

If you run your Django app, you can see the length in meters.

Conclusion

Customized Django filters are very useful if you are working on a project.

I was working on one of the Django projects. One of the use cases that I came across is that I have to calculate the number of days since the last login. Django user has field last_login field. I created a custom template filter that finds the number of days since the last login by substracting last_login date from the current date. There can be many such use cases.

I tried to explain it in the utmost simplest way. For more detail about creating the custom template filters in Django, read Django documentation. which you can use in your project. If you have any questions, let me know in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *