Django 1.10.1'my_templatetag'不是注册的标签库.必须是以下之一:

Sli*_*dal 56 django templatetags django-allauth

我想要一个自定义的菜单,取决于您所属的组.我使用Django 1.10.1,allauth等.当我试图制作我的模板标签失败时,它说:¨

TemplateSyntaxError at /
'my_templatetag' is not a registered tag library. Must be one of:
account
account_tags
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
socialaccount
socialaccount_tags
static
staticfiles
tz
Run Code Online (Sandbox Code Playgroud)

'my_templatetag.py'看起来像这样:

from django import template
from django.contrib.auth.models import Group


register = template.Library()

@register.filter(name='has_group')
def has_group(user, group_name):
    group =  Group.objects.get(name=group_name)
    return group in user.groups.all()
Run Code Online (Sandbox Code Playgroud)

和我的.html文件中出现错误,说,

{%  load my_templatetag %}
Run Code Online (Sandbox Code Playgroud)

我试图重启服务器数百万次,我也尝试更改所有名称,该应用程序是settings.py中的INSTALLED_APPS的一部分.我究竟做错了什么?

lmi*_*asf 90

除了放入my_templatetag.py内部app_name/templatetags,每次修改模板标签时,请确保重新启动Django开发服务器(或确保它自己重新启动).如果服务器没有重启,Django将不会注册标签.

  • 重启服务器!太感谢了! (4认同)
  • 对我而言,这是* templatetags文件夹中缺少的*** __ init __。py *** ... (2认同)
  • 这。人们可能会花费令人尴尬的长时间来调试一些如果你重新启动就可以工作的东西...... (2认同)

Dat*_* TT 50

从django 1.9开始,您可以在以下设置中加载这些新标签/过滤器:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    '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',
            'app.apptemplates.load_setting',

        ],

        'libraries':{
            'my_templatetag': 'app.templatetags.my_templatetag',

            }
    },
},
Run Code Online (Sandbox Code Playgroud)

]

  • 这应该是答案:我使用 Django 3.x。 (4认同)
  • 它也对我有用。这实际上可能是问题的选定答案。我正在使用 django 的 2.0 版本,以防人们想知道。 (2认同)

Hea*_*ify 24

确保您没有错过以下任何步骤:

  1. 在与应用程序文件夹中的models.py和views.py相同的级别创建一个名为"templatetags"的文件夹

  2. 您的应用程序必须位于settings.py中的INSTALLED_APPS中

  3. templatetags文件夹必须具有__init__.py

  4. 重启django服务器

  • 每次重启都是让我兴奋的!在#4上提醒我的^^ (2认同)

小智 8

您必须手动停止开发服务器并重新启动它,以便 Django 可以识别新的模板标签


Sha*_*jib 6

就我而言,问题是,我正在使用 {% load filter_method_name %}

我不得不换成 {% load filename %}

然后,我不得不重新启动服务器。

  • *重新启动服务器*,这样一个简单的解决方案就解决了一个恼人的错误 (3认同)

zub*_*hav 5

'my_templatetag.py' 存储在哪里?它应该存储在应用程序内名为“templatetags”的目录中。

如果不是这种情况,请参阅:https : //docs.djangoproject.com/en/dev/howto/custom-template-tags/


Rod*_*ell 5

我正在使用 Django 1.11,并且遇到了同样的问题。这里的一些答案是正确的,但有些东西可能会丢失。这是我所做的:

引用一位前用户的话:

在应用程序文件夹中创建一个名为“templatetags”的文件夹,与 models.py 和views.py 处于同一级别

您的应用程序必须位于 settings.py 中的 INSTALLED_APPS 中

templatetags文件夹必须有init.py

但是,在重新启动 Django 服务器之前,请将其添加到包含标签的文件中:

from django import template
register = template.Library()
Run Code Online (Sandbox Code Playgroud)

然后你可以重新启动服务器。