In this tutorial, you will learn how to django create custom template tags. There are lots of built-in template tags and filters in Django. But sometimes these tags are of no use or we need more functionality to do. For such a situation we create our own tags and filters.

When you define custom tags and filters using python to make them available to templates, use – Django Template Tags are simple Python Functions that accept arguments and after processing returns the values which can be displayed in templates. These tags are used in templates or in HTML. You can extend the template engine by defining custom tags and filters.

Django create custom template tags

Getting started.

The most common place for defining template tags are inside Django App. Create an app named core and add that app in INSTALLED_APPS. Inside core app, create a folder named templatetags at the level of And inside templatetags folder create file to ensure the directory is treated as a Python package.

Our custom template tags and filters will live in a module inside the templatetags directory. The name of the module file is that the name you’ll use to load the tags later, thus take care to choose the name of the file that won’t clash with custom tags and filters in another app.

For example, we will be creating a file named where we will be writing our tags and filters.

Our app layout should look like this –


And for loading the tags you should use like this in your template –

{% load custom_tags %}

Writing Django Custom Template Filters

Custom filters are just Python functions that take one or two arguments:

Here’s an example filter definition:

def uppercase(value, arg):
    """Removes all values of arg from the given string"""
    return value.replace(arg, '')

And here’s an example of how that filter would be used:

{{ somevariable|uppercase:"0" }}

Registering Django Custom Filters

For using the filters, we need to register it with Library instance, to make it available to Django Template.

from django import template

register = template.Library()

and for registering you can use decorator like this –


Here is the example of Django filter for making string lowercase and initial first character capital-

# templatetags/
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@stringfilter # use this if your filter only accepts strings
def lower(value):
    return value.lower()

from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

def initial_letter_filter(text, autoescape=True):
    first, other = text[0], text[1:]
    if autoescape:
        esc = conditional_escape
        esc = lambda x: x
    result = '<strong>%s</strong>%s' % (esc(first), esc(other))
    return mark_safe(result)

And here how you can use and load those filters in the template –

{% load custom_tags %}
<h2>Home Page - Template Tags</h2>

<p>Lower Template Tag (converts HaPpY to happy) - {{ "HaPpY" |lower }}</p>

<p>initial_letter_filter - {{"happy"|initial_letter_filter}}</p>

To read more about custom filters – Official Site

Writing Django Custom Template Tags

Django Template Tags are django template filters, which can do anything (complex task as well) as compare to filters. Django has shortcuts for making template tags. We can develop tags using those shortcuts. We will mostly use Django simple tags and django inclusion tags. Template tags can also take n number of arguments and return value.

Here’s an example tags definition:

def current_time(format_string):

And here’s an example of how that tags would be used:

current_time - {% current_time "%Y-%m-%d %I:%M %p" %}

Registering Django Custom Tags

For using the tags, we need to register it with Library instance, to make it available to Django Template.

from django import template

register = template.Library()

and for registering you can use simple_tag or inclusion_tag decorator like this –



Simple Tags ( simple_tag ) – Using this shortcut, you can easily create template tags. These tags can take one or more arguments and n number of positional arguments.

Inclusion Tags ( inclusion_tag ) – This is another tag that displays data by rendering another template.

Here is an example of Django Simple Tags –

from django import template

register = template.Library()

from datetime import datetime
def current_time(format_string):

register.simple_tag(lambda x: x - 1, name='minusone')

def some_function(value):
    return value - 2

def my_tag(a, b, *args, **kwargs):
    warning = kwargs['warning']
    profile = kwargs['profile']
    return warning

And here how you can use and load those simple tags in the template –

<p>current_time - {% current_time "%Y-%m-%d %I:%M %p" %}</p>

<p>minusone - {% minusone 2 %}</p>
<p>minustwo - {% minustwo 5 %}</p>

<p>Position arg - {% my_tag 123 "abcd" book.title warning="This is warning"|lower profile=1 %}</p>

{% current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>

Here is an example of Django Inclusion Tags –

from django import template

register = template.Library()

from django.contrib.auth.models import User
def show_results():
      obj = User.objects.values_list('username', flat=True)
      return {'choices': obj}

We are including results.html, so here is results.html

{% for choice in choices %}
    <li> {{ choice }} </li>
{% endfor %}

And here how you can use and load those inclusion tags in the template –

<p>Inclusion Tag - {% show_results %}</p>

GitHub – Run Example Locally

Code is also available on GitHub –

Clone the Repository

git clone

Change Directory

cd How-to-write-Django-Custom-Template-Tags-and-Filters

Create Virtual Environment – VirtualENV

virtualenv env

Activate Virtual Environment

source env/bin/activate

Run requirements file to install libraries using Pip3

pip3 install -r requirements.txt

Run the server

python3 runserver

And open http://localhost:8000/ in your browser.

Tags – template tags django, django templatetags, django inclusion tag, django template tags, custom template tags django