0

I'm trying to follow and learning about dynamic filtering in Django from the docs. https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering I've just been following along step by step and copy/pasted the code from docs. But I don't understand the last bit about added the publisher into the context, meaning I can't figure out how to query that data in the template. The only thing I can get a "hold" of publisher.

Because in the PublisherDetail view publisher_detail.html you would just do something straight forward like this, to list all the books from a publisher:

{% for book in book_list %}
    {{ book.title }}
{% endfor %}

This is part that is tripping me up.

We can also add the publisher into the context at the same time, so we can use it in the template:

# ...

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(PublisherBookList, self).get_context_data(**kwargs)
    # Add in the publisher
    context['publisher'] = self.publisher
    return context
mtt2p
  • 1,818
  • 1
  • 15
  • 22
  • 1
    It's not clear where you are having trouble and what you are asking about, unfortunately. What *exactly* is "tripping you up" about this? – Daniel Roseman Mar 02 '17 at 11:25
  • I guess I misunderstood, what exactly was supposed to happen. So it was my own reading and comprehension skills that were "tripping my up". I apologies. –  Mar 03 '17 at 07:49

2 Answers2

1

Setting context['publisher'] = self.publisher in get_context_data means you can display the publisher's details in the context. For example, you could display the publisher's name above the list of book titles with:

<h2>Books published by {{ publisher.name }}</h2>

{% for book in book_list %}
    {{ book.title }}
{% endfor %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

You can access related objects as described here: What is `related_name` used for in Django? .

Try calling either publisher.books.all() or publisher.book_set.all():

{% for book in publiser.book_set.all %}
    {{ book.title }}
{% endfor %}
Community
  • 1
  • 1
Udi
  • 29,222
  • 9
  • 96
  • 129