我创建了一个自定义简单标记,用于计算对象并返回它。我希望计数显示在导航栏内。因此可以通知用户。
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的徽章。但它没有显示任何东西。
您的代码中几乎没有简单的错误。
现在,只需按照以下步骤解决此问题。
{{ new_notification }}
替换{% new_notification %}
。
注意:{{ template_context_variable }}
语法用于使用模板上下文变量的值。所以使用{% template_tag params %}
语法。根据您的Django版本,查看https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/上的相关文档(从右下角选择特定版本)。def new_notification(request):
替换def new_notification():
,因为在模板base.html
中使用模板标记时没有将任何额外参数传递给函数。现在,刷新你的页面,你可以看到结果,它在我的情况下正在工作。