[Answered ]-Django – Many-to-many with intermediate model – display in template with Generic DetailView

1πŸ‘

βœ…

So, the answer was actually easier than it seemed.

The through-field data is actually available in the template via the
Generic View (as I suspected). The [through-model]_set gets it, and then you can just access all the attributes. Here is my Jinja template code

{% for contribution in hymntext.contribution_set.all %}
   <br>{{ contribution.role.name }}: {{ contribution.contributor.name }}
{% endfor %}

which outputs (in this particular fake example):

creator: David Haas
translator: John Newton

1πŸ‘

One of these (executed in your view class before they’re passed to the template as context variables) might help:

Here is a part of the Django docs that my help you. In order to get information like role from a HymnText contributor:

contributor.contribution_set.get(work=hymntext).role

OR you can call the Contribution model:

# Loop through the hymntext contributors...
roles = []; names = []
for contributor in hymntext.contributors:
  contribution = Contribution.objects.get(work=hymntext, contributor=contributor)
  roles.push(contribution.role)
  names.push(contributor.name) # I assume you define this in your Entity model

# Then set up your context variables and render the template
πŸ‘€Ryan Schuster

Leave a comment