TemplateSyntaxError 'apptags' 不是注册的标签库

TemplateSyntaxError 'apptags' is not a registered tag library

我在 templatetag 文件夹内的 apptags.py 文件中制作了一个自定义模板标签,templatetag 文件夹在我的应用程序文件夹内,代码如下

from django import template
import datetime
register=template.Library()
@register.simple_tag(name="get_date")
def get_date():
    now = datetime.datetime.now()
    return now

并且我在我的 html 文件中使用它作为

% load static %}
{% load apptags %}
{% get_date as today %}
<h2>Today is {{today}} </h2>

它显示以下错误:

TemplateSyntaxError 在 /exam/show-test/ 'apptags' 不是已注册的标签库。必须是以下之一: admin_list admin_modify admin_urls 缓存 国际化 l10n 日志 静止的 兹

P.S :- Temptetag 是一个包,因为我在里面制作了一个 init.py 文件

您需要在项目 settings.py 文件中添加模板标签,以便 Django 识别它。

将此添加到 settings.py 文件中 TEMPLATESOPTIONS 条目:

'libraries':  {
                '<template_tag name>': '<App_name>.templatetags.<template_tag name>',
            }

示例:

'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'libraries':  {
                'dict_key': 'blogs.templatetags.dict_key',
            }

根据 django 文档:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the init.py file to ensure the directory is treated as a Python package

在你的例子中,文件夹名称是错误的 templatetag
所以你应该重命名它到templatetags .
否则你应该按照 的回答为:

Alternatively, template tag modules can be registered through the 'libraries' argument to DjangoTemplates. This is useful if you want to use a different label from the template tag module name when loading template tags. It also enables you to register tags without installing an application