PythonAnywhere
PythonAnywhere

Reputation: 309

In the Django generic detail view where does context's index come from?

In the example below where does context's index 'book_list' comes from, if is arbitrary what is the naming convention?

class PublisherDetail(DetailView):

model = Publisher

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(PublisherDetail, self).get_context_data(**kwargs)
    # Add in a QuerySet of all the books
    context['book_list'] = Book.objects.all()
    return context 

Upvotes: 0

Views: 95

Answers (2)

Alasdair
Alasdair

Reputation: 309109

In that example, the variable name book_list is arbitrary. You could use books or anything else you like instead.

Using book_list is consistent with the ListView, which makes the list available in the template context as <lowercase model name>_list . See the docs on making friendly template contexts for more info.

Upvotes: 1

YPCrumble
YPCrumble

Reputation: 28732

The naming convention you're referring to (_list) is based on the ListView's template_name_suffix. That inherits from MultipleObjectTemplateResponseMixin.

In practice if you use a ListView like this one based on your example:

class PublisherList(ListView):

    model = Publisher

...you would able to refer to publisher_list in your template for the queryset of all publishers.

In your example you're including a list of all the books in your database using the same naming convention, but you could call that context variable (book_list) anything you wanted.

Upvotes: 2

Related Questions