Skip to content

Instantly share code, notes, and snippets.

@AshishPandagre
Last active May 30, 2021 18:18
Show Gist options
  • Save AshishPandagre/f26f49a716c07c444edd97298dad335b to your computer and use it in GitHub Desktop.
Save AshishPandagre/f26f49a716c07c444edd97298dad335b to your computer and use it in GitHub Desktop.
Creating a custom template tag in Django.
{% load my_template_tag %} <!-- Loading the file we defined our template tags in -->
{% for pdt in products %}
<tr>
<td>{{pdt.name}}</td>
<td>{{pdt.price}}</td>
<td>{{pdt.sold_by}}</td>
<td>{% n_reviews pdt.id %}</td>
<!-- our template tag, pdt.id is passed as argument in n_reviews function -->
</tr>
{% endfor %}
from django import template
from some_app.models import Product, Review # say, we have, Product, Review in our some_app/models.py
register = template.Library()
@register.simple_tag
def n_reviews(product_id):
# write down your queries.
# example queries..
# here, let's say we wanna count the number of reviews on a certain product. We can do something like this.
product = Product.objects.get(id=product_id)
reviews = Review.objects.filter(reviewed_on=product)
return reviews.count()
<--------------We use custom template tags for the part of information that we need to access a lot of times--------------->
<--------------Ex: To show the number of products in a cart, which is present on the navbar of all pages------------------->
1) Before making a custom template tag, make sure you've added your app name to INSTALLED_APPS (in settings.py).
2) Let app name be my_app , create a directory named 'templatetags' in my_app.
3) Inside 'templatetags', create '__init__.py' and 'my_template_tag.py'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment