Open In App

How to Add Multiple Arguments to Custom Template Filter in a Django Template

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, template filters are useful for modifying data before displaying it in templates. While built-in filters cover common cases, custom logic is sometimes necessary, particularly when handling multiple arguments.

Django only allows one argument to our filter. But we can use different techniques to pass multiple arguments to our custom filters, like passing values as a string separated by comma(,), hash(#), or any other delimiter.

In this article, we will explore how to create a Django custom filter and pass multiple arguments.

Understanding Django Template Filters

What is a Django Template Filter?

A template filter in Django is a way to transform the value of a variable in a template. For example, the lower filter converts a string to lowercase:

{{ "HELLO" | lower }}

Output:

hello

In some cases, built-in filters may not cover our specific needs, so Django allows us to create our own custom template filters.

What is a Custom Template Filter?

A custom template filter allows us to define specific logic for transforming data in a Django template. This approach is particularly useful for handling operations like formatting, string manipulations, or calculations. Custom filters are a clean way to apply business logic directly within templates without cluttering views or models.

Now, let's see how to pass multiple arguments to custom filter.

{{ 5 | multiply:'2,3,4' }}

In the filter function, we can customize our logic like this.

Python
@register.filter(name='multiply')
def multiply(value, args):
    """Multiplies the given value by the factor."""
    numbers = []
    if agrs:
      	numbers = args.split(',')
    try:
      	for number in numbers:
          	value *= int(number)
    except:
      	pass
    return value

Output:

120

This is how we can any number arguments in a single string, customize our logic in the backend.

Step 1: Create a Django Project and App

To start, create a new Django project and app. Use the following commands to set it up:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Add myapp to the INSTALLED_APPS in the settings.py:

Python
# settings.py
INSTALLED_APPS = [
    ...
    'myapp',
]

Complete Project Structure:

fiolll
File Structure

Step 2: Writing a Custom Template Filter

Now, let's create a custom template filter that can accept multiple arguments. First, create a directory for custom template tags inside our app and register the custom filter.

myapp/
templatetags/
__init__.py
custom_filters.py

In the custom_filters.py file, import Django’s template library and define our custom filter.

Python
from django import template

register = template.Library()

@register.filter(name='multiply')
def multiply(value, args):
    numbers = []
    if args:
        numbers = args.split(',')

    print(numbers)
    try:
        for number in numbers:
            value *= int(number)
    except:
        pass
    
    return value 

@register.filter(name='add')
def add(value, args):
    numbers = []
    if args:
        numbers = args.split(',')
    print(numbers)
    try:
        for number in numbers:
            value += int(number)
    except Exception as e:
        print(e)
    print('add', value)
    
    return value

Step 3: Create Views File

This file will handle rendering a template where the custom filter and simple tag are applied.

myapp/views.py

Python
from django.shortcuts import render

def my_view(request):
    return render(request, 'index.html', context)

Step 4: URL Configuration

Add a URL route to access the view:

Python
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.my_view, name='my_view'),
]

Step 5: Update the Template

Now, create the template custom.html in the templates/myapp/ directory to demonstrate the custom filters in action:

myapp/templates/index.html - Don't forget to load custom_filters to use them.

HTML
{% load custom_filters %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Filter Example</title>
</head>
<body>

    <p>5*2*3*4 = {{ 5|multiply:"2,3,4" }}</p>
  	<p>5+2+3+4 = {{ 5|add:"2,3,4" }}</p>

</body>
</html>

This template demonstrates how the custom filters work, specifically concatenating two strings with a hyphen.

Run the Server

Python manage.py runserver

Output:

Screenshot-2024-09-26-154608
Pass multiple argument to the custom filter in Django

Conclusion

In this article, we explored how to build a custom Django filter that concatenates two strings with a hyphen. By implementing such filters, we can add flexible string manipulation and other transformations directly in templates, maintaining clean code in views and models. We also covered how to pass multiple arguments using a delimiter and tested the functionality.


Next Article
Practice Tags :

Similar Reads