模板标签中的对象计数

Object count in template tags

我创建了一个自定义的简单标签来计算一个对象并 returns 它。我希望计数显示在导航栏内。因此可以通知用户。

  1. 我做了一个模板标签并注册了
  2. 我在 base.html
  3. 中加载了标签
  4. 我在导航栏中使用了标签,因为我希望在那里显示计数。
  5. 它只过滤字段 "live" 为 false
  6. 的对象
  7. 我在应用程序目录中创建了一个 templatetags 目录。
  8. 我在 templatetags
  9. 里面添加了一个 __ init __.py

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>

我希望计数会显示在文本旁边,在带有 bootstrap 的徽章内。但是它没有显示任何内容。

您的代码中几乎没有简单的错误。

现在,只需按照以下步骤解决此问题。

  1. base.html.

    中将{{ new_notification }}替换为{% new_notification %}

    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. def new_notification(request): 替换为 notifications.py 中的 def new_notification():,因为您没有向函数传递任何额外参数,同时在模板 base.html.

  3. 中使用模板标签

现在,刷新您的页面,您可以看到结果,就我而言,它正在运行。