49

I'm trying to do something like this:

class AboutView(TemplateView):
    template_name = 'about.html'

    def get_context_data(self, **kwargs):
        context = super(AboutView, self).get_context_data(**kwargs)
        context['dahl_books'] = Books.objects.filter(author="Dahl')

When I try to access dahl_books in my template like this:

{% for book in dahl_books %}

dahl_books is not available in the template context, even though the Books QuerySet returned a non-zero number of books. ....am I doing something wrong in either my template or in get_context_data?

knite
  • 6,033
  • 6
  • 38
  • 54
9-bits
  • 10,395
  • 21
  • 61
  • 83
  • This question was so extremely helpful, I wish I could vote it up a hundred times... I've been searching for ways to display re-defined get_context_data to the template, but had such a hard time finding it... thanks so much! (And I disagree with the close vote -- it's very much a question). – Tim S. Nov 05 '15 at 22:01
  • 1
    I found this new feature interesting: http://reinout.vanrees.org/weblog/2014/05/19/context.html – Paolo May 05 '16 at 20:08
  • I agree with @TimS. except probably just upvote 10 times since that's about how many posts I've looked at trying to figure out how to access my context variable without a clear answer. – Casivio Sep 28 '20 at 16:54

1 Answers1

73

I can't test it, but I bet you need

return context

at the end of get_context_data :)

Jakub Gocławski
  • 3,282
  • 1
  • 18
  • 12
  • I have a follow up, can I declore context as a class variable instead of local and returning it? – rtindru Oct 19 '14 at 17:31
  • You will have to implement its use as a class variable but you can get context data however you want. Just realize that django looks for get_context_data so you'll have to override how django is looking for it in your get and post methods. – Ian Kirkpatrick Jul 26 '17 at 17:16