0

The basic concept of context in Django are well explained here and here, as well as Django doc. But I don't understand the following code that works in the Mozilla Django tutorial:

class BookListView(generic.ListView):
    model = Book

def get_context_data(self, **kwargs):
    context = super(BookListView, self).get_context_data(**kwargs)
    context['author_books'] = Book.objects.filter(author=self.kwargs['pk'])
    return context

Why is it necessary to define context twice? Is it the same as: author_books = # 'author_books' defined book_list = # 'book_list' defined

    context ={
        'author_books': author_books,
        'book_list': book_list,
    }

Testing in Django shell didn't work for me as I'm still struggling with how to extract data from foreign-key items.

YCode
  • 1,192
  • 1
  • 12
  • 28
  • 2
    It's not defined twice, the get_context_data method from the base class generic.ListView is overriden to add an extra entry named 'author_books', that is computed based on the 'pk' parameter of the HTTP request – Nielk Jul 08 '21 at 17:57
  • So is the first `context` not necessary? Do you suppose it is just an example the Tutorial gives? – YCode Jul 08 '21 at 18:18
  • No, in the first line you initialize the variable context to what the parent class ListView returns: a dict with some entries. – Nielk Jul 08 '21 at 18:21

0 Answers0