How to create links to more than one related detail template page in a detail template page?

Hi there, Django newbie here,

I followed this tutorial for creating a library App in Django.

I have tweaked this a bit, because I need to be able to register more than one author for some books. Now my problem is how to deal with this in de book-detail template page?

In the book-detail.html file I have replaced the line:
<p><strong>Author:</strong> <a href="">{{ book.author }}</a></p>

into:
<p><strong>Author:</strong> <a href="">{{ book.author.all|join:", " }}</a></p>

but then the result is that I get all authors of the book mentioned allright, but in one big link, covering all author names, but not leading to any author-detail page. How do I change this so that I get separate links to the detail pages of all the authors of the book?

Thanks in advance for any help,

Wim

Welcome @cannedit !

One option is to use a {% for ... %} tag to iterate over book.author.all. Each element in that loop would be an individual instance that could be rendered.

Another option would be to create a model method on Book to create the list of authors as a list of URLs, and then render it.

Hi Ken,

Thank you, but would you be able to elaborate a bit more on these suggestions, or point me to sites where I could see examples of them or see them more or less in action (still learning)?

Thanks and best wishes,
Wim

No worries.

To do that however, I’m going to need to know more about the models being used here - can you confirm that you are using the models exactly as described at Django Tutorial Part 3: Using models - Learn web development | MDN ? (Have you made any changes to them? If so, please specify.)

Hi Ken,

Yes, the ‘more authors per book’ is the only tweak I needed to be able to use the App.

Best wishes,
Wim

They actually cover a lot of what you need for this later on at Django Tutorial Part 6: Generic list and detail views - Learn web development | MDN

If you work your way through that page, you’ll see where they’re using the BookInstance model to do fundamentally the same thing as what you’re trying to do:
{% for copy in book.bookinstance_set.all %}

The difference is that you want to iterate over book.author_set.all, and instead of rendering a paragraph or div, you only want to render a single <a> element, with the href attribute being the url and the text in the link being the author’s name.

Hi Ken,

Thanks, with this in mind I will go over that part again.

Best wishes,
Wim