5

After following the tutorial for Django, I have the baseline of my app up and running, but now I am trying to add some data to one of the templates. I thought I could add this by using extra_context but I am missing something (likely obvious, as I am new to Django). This is what I have in my app's 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',
        )),

The error I am getting is TypeError :
ListView() received an invalid keyword 'extra_context'

What I need to do is somehow get those sums out to the template so that I can display them. How can I do this properly or easily?

Anthony Lozano
  • 571
  • 1
  • 5
  • 16

2 Answers2

11

extra_context requires a dict, i.e.:

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

EDIT

Sorry, actually, I don't think as_view actually supports that kwarg. You can try it, but most likely you'll need to subclass the view and override get_context_data as the docs describe:

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
Yushin Washio
  • 675
  • 8
  • 12
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 1
    This is not really an answer. The question is about using the extra_context keyword described in the docs. – fariza Feb 11 '13 at 15:24
  • 4
    In fact, the right answer is. The extra_context keyword is no longer supported by the class based generic views – fariza Feb 11 '13 at 17:20
  • 1
    As described in the answer to this question: [Moving from direct_to_template to new TemplateView in Django](http://stackoverflow.com/questions/11005733/moving-from-direct-to-template-to-new-templateview-in-django), the only way to add extra_context is to subclass generic views and provide your own get_context_data method – stephendwolff Jun 06 '13 at 10:28
1

Django, 1.5 seems do not support extra_context in as_view. But you can define a subclass and override get_context_data. I think this is better:

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

Still, the extra_context should be a dict.

Hope this helps :)

TylerTemp
  • 970
  • 1
  • 9
  • 9