Open In App

How to create Custom Template Tags in Django ?

Improve
Improve
Like Article
Like
Save
Share
Report

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
  
# Create your models here.
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 – 



Last Updated : 04 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads