Django TemplateSyntaxError - 'staticfiles' 不是注册的标签库

Ala*_*air 112 python django django-templates django-3.0

升级到 Django 3.0 后,我得到以下信息TemplateSyntaxError

In template /Users/alasdair//myproject/myapp/templates/index.html, error at line 1
'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz
Run Code Online (Sandbox Code Playgroud)

这是我的模板

{% load staticfiles %}
<img src="{% static 'my_image.html' %}">
Run Code Online (Sandbox Code Playgroud)

Ala*_*air 266

如果您的模板中有以下任何标签:

{% load staticfiles %}
{% load static from staticfiles %}
{% load admin_static %}
Run Code Online (Sandbox Code Playgroud)

然后将其替换为:

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

您必须进行此更改,因为{% load staticfiles %}在 Django 2.1{% load admin_static %}已弃用,并在 Django 3.0 中删除


小智 16

  • 尝试{% load static %}代替{% load staticfiles %}
  • 如果 CSS 或任何其他文件的效果没有反映在您的模板中,那么还要在settings.py文件末尾写下以下几行
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
Run Code Online (Sandbox Code Playgroud)

  • 添加 STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] 解决了这个问题。在我将静态文件目录添加到模板内的 DIRS 之前,这不起作用。非常感谢! (2认同)
  • 这应该被标记为正确答案。其他选项现已废弃。 (2认同)

Aba*_*owu 6

这对我使用 django 3.1.4 有效。

{% load static %}
<link rel"stylesheet" href = "{% static 'style.css' %}">
Run Code Online (Sandbox Code Playgroud)


Bac*_*ech 5

将静态文件注册到标签库

staticfiles已更改为静态

您可以在您的 setting.py 中使用空闲代码进行注册

在您的 TEMPALTE 设置中添加此代码


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',
            ],
            'libraries' : {
                'staticfiles': 'django.templatetags.static', 
            }
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

请注意,您可以找到您没有的图书馆