Creating custom template tags in Django

Install Django

After you've activated a virtual environment, enter the command:

You must be creating app.

python startapp post





In the project


from django.contrib import admin
from django.urls import path

from django.conf.urls import include

urlpatterns = [
    path('post/', include('post.urls')),

Create url for new app

from django.urls import path

from django.views.generic import TemplateView

app_name = "post_count"

urlpatterns = [
    path('count/', TemplateView.as_view(template_name='count.html'))

Create the Model

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=400, default=0)
    def __str__(self):
        return self.title

# django_project/post/
from django.contrib import admin

from .models import Post

To apply migration, we need to run migrate command as follows

python makemigrations
python migrate


python runserver


adding data using Django Administration's panel

Create a new empty file

create template tag


from django import template
register = template.Library()

from post.models import Post

def get_post_count(context):

    result =  Post.objects.all().count()
    return result


Create one HTML file named count.html

Post count is<br>
{% load post_count %} {% get_post_count %}