You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义模板标签报错:无效块标签,如何全局传递上下文?

解决Django自定义模板标签加载错误及全局上下文显示问题

核心错误原因与修复步骤

1. 模板未加载自定义标签库

使用自定义标签前必须先在模板中加载对应的标签库,否则Django无法识别{% news %}标签。修改base.html:

{% load news %}  <!-- 必须添加在模板最顶部 -->

{% news %}

{% for new in news %}
    <p>{{ new.title }}</p>
{% endfor %}

2. 调整自定义标签模板文件位置

你把news.html放在了templatetags目录下,这不符合Django的模板查找规则。需要将其移到app的templates目录中,比如main/templates/main/news.html,然后修改自定义标签的路径:

# main/templatetags/news.py
from django import template
from support.models import News

register = template.Library()

@register.inclusion_tag('main/news.html', takes_context=True)  # 更新为正确的模板路径
def news(context):
    return {
        'news': News.objects.order_by("-date_posted")[:25],
    }

3. 修复视图重复定义问题

你在views.py中重复定义了HomeView类,后定义的会覆盖前一个,保留一个即可,或重命名其中一个:

# main/views.py
class HomeView(ListView):
    model = Product
    context_object_name='products'
    template_name = 'main/home.html'
    paginate_by = 25

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        categories = Category.objects.all()
        news = News.objects.all()
        context.update({
            'categories' : categories,
            'news' : news,
        })
        
        return context

# 若需无额外上下文的视图,重命名避免冲突:
# class SimpleHomeView(ListView):
#     model = Product
#     context_object_name='products'
#     template_name = 'main/home.html'
#     paginate_by = 25

4. 完善templatetags目录配置

  • 在main/templatetags/目录下创建空的__init__.py文件,让Django识别这是一个可导入的模块
  • 确保main app已添加到settings.py的INSTALLED_APPS中:
# project/settings.py
INSTALLED_APPS = [
    ...
    'main',
    ...
]

内容的提问来源于stack exchange,提问作者nameless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:35:23