在Django应用程序中出现 "'tag' is not a registered tag library. Must be one of" 错误。

5

我在模板标签中添加了我的简单标签。我的第一个标签可见并且正常工作,但第二个标签无法正常工作。在我将标签添加到模板{% load deposit_earn %}后,我收到信息''deposit_earn' is not a registered tag library. Must be one of:'.

我的标签文件如下:

@register.simple_tag()
def multiply(number_instalment_loans, rrso, balance):
    rrso_percent = rrso/100
    return round(discounted_interest_rate(12, number_instalment_loans, rrso_percent, balance))

@register.simple_tag()
def deposit_earn(period, interest, balance):
    interest_percent = interest/100
    equals = balance * interest_percent * period / 12
    return round(equals)

为什么我的第一个标签能够工作而第二个标签不能?我尝试在注册标签后重置服务器,但没有帮助。
3个回答

8

https://docs.djangoproject.com/zh-hans/2.2/howto/custom-template-tags/

你应该导入模板标签文件名,而不是方法名。

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

假设 multiply 和 deposit_earn 在 poll_extras.py 文件中实现

那么在你的模板中,只需要调用 poll_extras 即可

{% load poll_extras %}

{{ something|multiply }}
or
{{ something|deposit_earn }}

1
我遇到了类似的问题,而且我还需要记得将包含模板标签的应用程序添加到INSTALLED_APPS中。如果有帮助的话。 - thespacecamel

4
你可能需要在按照文档中给出的所有建议之后重启服务器... 当我只需要重新启动服务器时,这实际上让我花了大约10分钟来弄清楚问题所在。

0
值得一提的是,如果 templatetags 目录不存在,在创建它之后,不要忘记包含空的 __init__.py 脚本,以便该目录被视为 Python 包。否则,您仍将获得 Django 错误页面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接