Skip to content
Related Articles

Related Articles

Custom Template Filters in Django

Improve Article
Save Article
Like Article
  • Last Updated : 01 Feb, 2021

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.

  • Filter is also the important feature of our template language.
  • Filters are basically used to modify or filter your variables.
  • You have to use this pipe ( | ) symbol to apply filter in any variables.

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

Python3




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

Python3




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

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

Python3




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

myproj/urls.py

Python3




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 :-


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!