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

Django ListView异常:仅get_context_data生效,Product模型无法渲染

Django ListView get_context_data 数据覆盖问题解决

你的问题出在get_context_data方法中上下文字典被覆盖,没有正确合并父类返回的基础数据和自定义数据。

错误原因分析

  1. 第一种写法:

    def get_context_data(self, **kwargs):
        categories = Category.objects.all()
        news = News.objects.all()
        context = {
            'categories' : categories,
            'news' : news,
        }
        context = super().get_context_data(**kwargs)  # 直接覆盖了之前定义的context
        return context
    

    你先创建了包含categories和news的字典,但随后直接将context重新赋值为父类方法返回的结果(仅包含products数据),导致自定义的分类和新闻数据被丢弃,所以模板里只能显示Product相关内容。

  2. 第二种写法:

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  # 拿到包含products的上下文
        categories = Category.objects.all()
        news = News.objects.all()
        context = {
            'categories' : categories,
            'news' : news,
        }  # 重新定义字典,覆盖了父类的上下文
        return context
    

    先获取了父类的上下文,但随后重新创建了仅包含自定义数据的字典,丢弃了products数据,所以模板里只能显示分类和新闻。

正确写法

需要合并父类上下文和自定义数据,以下两种方式都可以:

方式1:先获取父类上下文,再添加自定义数据(推荐)

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

    def get_context_data(self, **kwargs):
        # 先调用父类方法,获取包含products的基础上下文
        context = super().get_context_data(**kwargs)
        # 将自定义数据添加到上下文中
        context['categories'] = Category.objects.all()
        context['news'] = News.objects.all()
        return context

方式2:合并两个字典

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

    def get_context_data(self, **kwargs):
        custom_context = {
            'categories': Category.objects.all(),
            'news': News.objects.all(),
        }
        # 合并父类上下文和自定义上下文,避免数据覆盖
        context = {**super().get_context_data(**kwargs), **custom_context}
        return context

模板逻辑验证

你的模板写法是正确的:

  • categories.html通过{% for category in categories %}和{% for new in news %}渲染自定义数据
  • home.html通过{% for product in products %}渲染Product数据
    只要上下文同时包含这三个键,就能正常渲染所有内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:35:36