模板标签中的对象计数

问题描述 投票:1回答:1

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

  1. 我制作了一个模板标签并进行了注册
  2. 我在base.html中加载了标记
  3. 我在导航栏中使用了标签,因为我希望计数显示在那里。
  4. 它只过滤通过“生命”字段为false的对象
  5. 我在应用程序目录中创建了一个templatetags目录。
  6. 我在templatetags中添加了__ 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的徽章。但它没有显示任何东西。

python-3.x django-2.0
1个回答
1
投票

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

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

  1. 用base.html中的{{ new_notification }}替换{% new_notification %}。 注意:{{ template_context_variable }}语法用于使用模板上下文变量的值。所以使用{% template_tag params %}语法。根据您的Django版本,查看https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/上的相关文档(从右下角选择特定版本)。
  2. 使用来自notifications.py的def new_notification(request):替换def new_notification():,因为在模板base.html中使用模板标记时没有将任何额外参数传递给函数。

现在,刷新你的页面,你可以看到结果,它在我的情况下正在工作。

© www.soinside.com 2019 - 2024. All rights reserved.