Making your own custom filter tags in Django

Server Side ProgrammingPythonProgramming

Filters are really very helpful, there are many built-in filters in Django. We can also make our own filters in Django which we can use in Django projects in any template file. Filters are used in many ways like making lowercase to uppercase in HTML.

In this article, we will see how to make a custom template filter tag in Django. So, let's get started.


First of all, create a Django project and an app.

Add a templates and templatetags directory in your apps root project. The project structure would look like this −

example is our app and tutorial is our project.

Make sure your TEMPLATES variable in looks like this −

import os
      'BACKEND': 'django.template.backends.django.DjangoTem
      'DIRS': [os.path.join(BASE_DIR, 'example/templates')]
      'APP_DIRS': True,
      'OPTIONS': {
         'context_processors': [

Add "example" to INSTALLED_APPS variable of It just sets up the templates folder.

In the templates folder, add a home.html and leave it like that for now.

In of example, add the following lines −

from django.shortcuts import render

# Create your views here.
def main(request):
   return render(request,"home.html")

Here we simply rendered our main frontend in main view.

In of the project, add the following lines −

from django.contrib import admin
from django.urls import path, include
urlpatterns = [

Here we included our apps in main urls.

In of example or app, add the following −

from django.urls import path,include
from . import views
urlpatterns = [
   path('', views.main,name="main")

It sets up the basic path urls and render our main view.

Create in templatetags folder and a filter file named "". Add the following code in it −

from django.template import Library


def upper(value):
   return value.upper()

Here we imported a Library and registered it. We created a function or we can say a filter named upper and we registered it using decorator. Each filter takes some value; we can define how many values it can take.

Come back to your home.html and add −

<!DOCTYPE html>
      {% load upperfilter %}
      <h1>{{"hi friends how are you" | upper}}</h1>

Here on the frontend, we loaded our filter using {% %}, and then in <h1> element, we used the filter.

This filter will convert lowercase to uppercase.


Without filter

With filter

Published on 26-Aug-2021 12:50:56