Search code examples
python-3.xdjango-2.0

Object count in template tags


I created a custom simple tag that counts an object and returns it. I want the count to be shown inside the navbar. So the user can be notified.

  1. I made a template tag and registered it
  2. I loaded the tag inside the base.html
  3. I used the tag inside the navbar, Since I want the count to be shown there.
  4. It only filters through objects that have the field "live" on false
  5. I created a templatetags directory inside the the application directory.
  6. I added a __ init __.py inside templatetags

notifications.py (templatetags/notifications.py)

from django import template
from home.models import ReportRequests

register = template.Library()

@register.simple_tag
def new_notification(request):
    a = ReportRequests.objects.filter(live=False).count()
    return a



base.html

{% load notifications %}

<a href="{% url 'home:report_request' %}"><i class="fas fa-inbox"></i><p>Requests</p><span class="badge badge-pill badge-danger">{{ new_notification }}</span></a>

I expect that the count will be shown next to the text, inside badge with bootstrap. But its not showing anything.


Solution

  • Few simple mistakes are there in your code.

    Now, just follow the below steps to fix this.

    1. Replace {{ new_notification }} with {% new_notification %} in base.html.

      Note: {{ template_context_variable }} syntax is used to use value of template context variables. So use {% template_tag params %} syntax. Based on your Django version check the related documentation at https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/ (select specific version from very bottom-right).

    2. Replace def new_notification(request): with def new_notification(): from notifications.py as you are not passing any extra parameter to the function while using template tag in template base.html.

    Now, refresh your page and you can see the result and it is working, in my case.