How to create and use Custom Template Tags in Django Framework ?
Django has a template language for building HTML views and it provides us with the features such as template tags these tags can be used to manipulate or get extra information to be displayed on the template.
Template tags can process data and return its output. Django provides many of such templates tags by default and you can also create a custom template tag as per your requirement.
And in this post, You’ll learn how to create custom template tags in Django Framework.
Creating a Project
Creating an App
For a better explanation, I’m creating an app with name products and we’ll learn to create template tags for products.
django-admin startapp products
Next, add the app products under INSTALLED_APPS in settings.py.
INSTALLED_APPS = [ ... 'products.apps.ProductsConfig', ]
Creating Models and Database Migrations
In products\models.py
from django.db import models class ProductModel(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) price = models.FloatField(default=0.0) featured_image = models.CharField(max_length=255, null=True) class Meta(): db_table = "products" ordering = ( '-product_id', )
After ProductModel
class make a migrations file using command python manage.py makemigrations products
. And then to create a database table run python manage.py runserver
.
In products\urls.py
from django.urls import path from products import views app_name = "products" urlpatterns = [ path( '', views.product_list, name="list" ), ]
In products\views.py
from products.models import ProductModel from django.shortcuts import render # Create your views here. def product_list(request): info = { 'list' : ProductModel.objects.filter() } return render(request, 'products/list.html', info)
Creating custom template tag
By default, Django looks for templatetags directory within the apps folder.
In products\templatetags\product_tags.py
from django import template import datetime from django.conf import settings from products.models import ProductModel register = template.Library() @register.simple_tag def products_count(): return ProductModel.objects.count() @register.simple_tag def get_product_image( image ): url = f"{settings.MEDIA_URL}/not_found.png"; if image: product = ProductModel() product.featured_image = image url = product.featured_image_url return url
The functions must be registered as tags using register = template.Library()
. The simple_tag will mark a function as a tag that can use used inside the template.
We have created two template tags the first products_count
tag simply returns the count of products. And the get_product_image
returns the URL of the image to be displayed.
If the image is None
then will return the default fallback image.
Using template tags in Templates
First, the template tag must be loaded using {% load product_tags %} only then you will be able to call the product template tags.
In products\templates\products\list.html
{% load product_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Products</title> </head> <body> <h2>Products | Current no of Products : <span style="color:red;" >{% products_count %}</span> </h2> <table border="1" > <thead> <tr> <th>S.No</th> <th>Image</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> {% if list %} {% for item in list %} <tr> <td>{{ forloop.counter }}</td> <td> <img src="{% get_product_image image=item.featured_image %}" style="width:150px;height:80px;" > </td> <td>{{ item.name }}</td> <td>{{ item.price }}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </body> </html>

output of products count and images of products displayed using custom template tags created in Django Framework