Creating custom template tags in Django

Install Django

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

You must be creating app.
 

python manage.py startapp post


modify settings.py

INSTALLED_APPS = (

    'post'
)

 


In the project urls.py:

#django_project/django_project/urls.py

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

from django.conf.urls import include


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


Create url for new app

#django_project/post/urls.py
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

#django_project/post/models.py
from django.db import models

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

admin.py

# django_project/post/admin.py
from django.contrib import admin

from .models import Post

admin.site.register(Post)

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

python manage.py makemigrations
python manage.py migrate

runserver

python manage.py runserver

 

adding data using Django Administration's panel
http://127.0.0.1:8000/admin

Create a new empty file
templatetags/__init__.py


create template tag

#templatetags/post_count.py

from django import template
register = template.Library()


from post.models import Post

@register.simple_tag(takes_context=True)
def get_post_count(context):

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

 

Create one HTML file named count.html

#django_project/post/templates/count.html
Post count is<br>
{% load post_count %} {% get_post_count %}

 

open

http://127.0.0.1:8000/post/count/



Comments