无法将extra_context添加到ListView

Ant*_*ano 2 django

在遵循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',
        )),
Run Code Online (Sandbox Code Playgroud)

我得到的错误是TypeError:
ListView()收到一个无效的关键字'extra_context'

我需要做的是以某种方式将这些总和输出到模板,以便我可以显示它们.我该如何正确或轻松地做到这一点?

Chr*_*att 10

extra_context 需要一个字典,即:

extra_context={'solicitations': Solicitation.objects...}
Run Code Online (Sandbox Code Playgroud)

编辑

对不起,实际上,我认为as_view实际上并不支持那个kwarg.您可以尝试一下,但很可能您需要get_context_data按照文档描述的方式对视图进行子类化并覆盖:

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
Run Code Online (Sandbox Code Playgroud)

  • 事实上,正确的答案是。基于类的通用视图不再支持 extra_context 关键字 (4认同)