How to create Custom Template Tags in Django ?
Last Updated :
04 Jan, 2021
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed. You can perform QuerySets or process any data to display results in your templates.
The most common place to specify custom template tags is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app.
Django provides the following helper functions that allow you to create your own template tags in an easy manner:
- simple_tag: Processes the data and returns a string
- inclusion_tag: Processes the data and returns a rendered template
- assignment_tag: Processes the data and sets a variable in the context
Explanation:
illustration of How to create a custom template tag using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create Basic Project using MVT in Django ?
How to Create an App in Django ?
Inside your django application (geeks app) directory, create a new directory, name it templatetags, and add an empty __init__.py file to it to ensure the directory is treated as a Python package. Create another file in the same folder and name it custom_tags.py. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. The file structure of the django application should look like the following:
geeks/
__init__.py
models.py
...
templatetags/
__init__.py
custom_tags.py
In your template you would use the following:
{% load custom_tags %}
There’s no limit on how many modules you put in the templatetags package. Just keep in mind that a {% load %} statement will load tags for the given Python module name, not the name of the app.
To be a valid tag library, the module(custom_tags.py) must contain a module-level variable named register that is a template Library instance in which all the tags are registered. So, near the top of your module, put the following:
from django import template
register = template.Library()
Inside the models.py add the following code:
Python3
from django.db import models
class YourModel(models.Model):
first_name = models.CharField(max_length = 30 )
last_name = models.CharField(max_length = 30 )
def __str__( self ):
return self .first_name
|
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
We will start by creating a simple tag to retrieve the total count of objects in our model named as YourModel. Edit the custom_tags.py file you just created and add the following code:
Python3
from django import template
register = template.Library()
from .models import YourModel
@register .simple_tag
def any_function():
return YourModel.objects.count()
|
Inside the urls.py flle of project named geeksforgeeks add the following code
Python3
from django.contrib import admin
from django.urls import path
from django.views.generic.base import TemplateView
urlpatterns = [
path( 'admin/' , admin.site.urls),
path('',TemplateView.as_view(template_name = "Intro.html" ),name = "intro" )
]
|
Create the folder named templates inside the app directory(geeks) and create the file named Intro.py and add the following code:
HTML
{% load custom_tag %}
<!DOCTYPE html>
< html lang = "en" dir = "ltr" >
< head >
< meta charset = "utf-8" >
< title >Intro</ title >
</ head >
< body >
{% any_function %} Persons in your model
</ body >
</ html >
|
Now run,
python manage.py runserver
Let’s check what is there on http://localhost:8000/ –
Output –

Django Models Entries in DB –

Similar Reads
Django Templates
Templates are the third and most important part of Django's MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamic HTML web pages that are visible to the end-user. Django mainly functions with
7 min read
variables - Django Templates
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
2 min read
Django Template Tags
Django Web Framework ships with dozens of tags used to implement arbitrary logics right in the template. Tags look like this: {% tag %} . Tags are more complex than variables: Some create text in the output, some control flow by performing loops or logic, and some load external information into the
7 min read
extends - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
2 min read
if - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read
for loop - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read
comment - Django template tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to the template but also provide som
2 min read
include - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
2 min read
url - Django Template Tag
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read
cycle - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read