Open In App

Custom Template Filters in Django

Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. 

What is filters in Django template language (DTL) ?

Before move to see the how to make custom filters in Django Template Language, let’s  learn what is filters in Django.



For example :-

So this filter will modify this variable value in lowercase



{{ variable_name |  filter_name }}

How to create custom Template Filter in Django?

First of install create the django project using following command :-

django-admin startproject myproj
cd myproj

Then create the new app  inside myproj

For Ubuntu

python3 manage.py startapp main

Add app name in settings.py inside INSTALLED_APPS

Add this view in your views.py




from django.shortcuts import render
  
# Create your views here.
def home(request):
    value="GEEKSFORGEEKS"
    return render(request,"home.html",{"value":value})

Now lets make the templatetags directory inside our main folder

and don’t forget to create __init__.py file inside templatetag directory

and then create lower_filter.py file




from django import template
  
register = template.Library()
  
@register.filter()
def low(value):
    return value.lower()

Create a directory in main directory add name it as templates

Inside the templates directory create a file and name it as home.html




<!DOCTYPE html>
<html>
<head>
    <title>Welcome To GFG</title>
</head>
<body>
    {% load lower_filter %}
    <h1>{{value|low}}</h1>
</body>
</html>

Create a file in main directory and name it as urls.py




from django.urls import path
from .views import *
  
urlpatterns = [
    path('', home,name="home"),
  
]

myproj/urls.py




from django.contrib import admin
from django.urls import path,include
  
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("main.urls"))
]

open cmd or terminal

For Ubuntu

python3 manage.py runserver

Output :-


Article Tags :