【问题标题】:Can't add extra_context to a ListView无法将 extra_context 添加到 ListView
【发布时间】:2012-02-06 22:43:30
【问题描述】:

遵循 Django 教程后,我的应用程序的基线已启动并运行,但现在我正尝试向其中一个模板添加一些数据。我以为我可以通过使用 extra_context 添加它,但我遗漏了一些东西(可能很明显,因为我是 Django 新手)。这就是我在应用程序的 urls.py 中的内容:

url(r'^$', ListView.as_view(
        queryset=Solicitation.objects.order_by('-modified'),
        context_object_name='solicitationList',
        template_name='ptracker/index.html',
        extra_context=Solicitation.objects.aggregate(Sum('solicitationValue'),Sum('anticipatedValue')),
        name='index',
        )),

我得到的错误是 TypeError :
ListView() 收到无效关键字“extra_context”

我需要做的是以某种方式将这些总和输出到模板中,以便我可以显示它们。我怎样才能正确或轻松地做到这一点?

【问题讨论】:

    标签: django


    【解决方案1】:

    extra_context 需要一个字典,即:

    extra_context={'solicitations': Solicitation.objects...}
    

    编辑

    对不起,实际上,我不认为 as_view 实际上支持那个 kwarg。您可以尝试一下,但很可能您需要子类化视图并将get_context_data 覆盖为docs 描述:

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherBookListView, self).get_context_data(**kwargs)
        # Add in the publisher
        context['publisher'] = self.publisher
        return context
    

    【讨论】:

    • 这不是一个真正的答案。问题是关于使用文档中描述的 extra_context 关键字。
    • 其实正确答案是。基于类的通用视图不再支持 extra_context 关键字
    • 如该问题的答案所述:Moving from direct_to_template to new TemplateView in Django,添加 extra_context 的唯一方法是子类化通用视图并提供自己的 get_context_data 方法
    【解决方案2】:

    Django,1.5 似乎不支持 as_view 中的 extra_context。但是您可以定义一个子类并覆盖 get_context_data。 我认为这样更好:

    class SubListView(ListView):
        extra_context = {}
        def get_context_data(self, **kwargs):
            context = super(self.__class__, self).get_context_data(**kwargs)
            for key, value in self.extra_context.items():
                if callable(value):
                    context[key] = value()
                else:
                    context[key] = value
            return context
    

    不过,extra_context 应该是一个字典。

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2011-03-25
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      相关资源
      最近更新 更多