【问题标题】:Object count in template tags模板标签中的对象计数
【发布时间】:2019-04-19 14:00:49
【问题描述】:

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

  1. 我做了一个模板标签并注册了它
  2. 我在 base.html 中加载了标签
  3. 我在导航栏中使用了标签,因为我希望在其中显示计数。
  4. 它只过滤字段“live”为 false 的对象
  5. 我在应用程序目录中创建了一个 templatetags 目录。
  6. 我在模板标签中添加了一个 __ 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>

我希望计数将显示在文本旁边,在带有引导程序的徽章内。但它没有显示任何内容。

【问题讨论】:

    标签: python-3.x django-2.0


    【解决方案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 中使用模板标记时,您没有向函数传递任何额外参数。

    现在,刷新你的页面,你可以看到结果,就我而言,它正在工作。

    【讨论】:

    • 谢谢!事实上,我以错误的方式使用了模板标签。祝你有美好的一天!
    猜你喜欢
    • 2012-08-06
    • 2011-09-24
    • 2013-06-09
    • 2022-01-22
    • 1970-01-01
    • 2017-01-07
    • 2014-01-13
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多