listing objects from ManyToManyField

DjangoDjango TemplatesMany to-Many

Django Problem Overview


I am trying to print a list of all the Conferences and for each conference, print its 3 Speakers.

In my template I have:

{% if conferences %}
        <ul>
        {% for conference in conferences %}
                <li>{{ conference.date }}</li>
                {% for speakers in conference.speakers %}
                        <li>{{ conference.speakers }}</li>
                {% endfor %}
        {% endfor %}
        </ul>
{% else %}
<p>No Conferences</p>
{% endif %}

in my views.py file I have:

from django.shortcuts import render_to_response
from youthconf.conference.models import Conference

def manageconf(request):
        conferences = Conference.objects.all().order_by('-date')[:5]
        return render_to_response('conference/manageconf.html', {'conferences': conferences})

there is a model named conference. which has a class named Conferences with a ManyToManyField named speakers

I get the error:

Caught an exception while rendering: 'ManyRelatedManager' object is not iterable

with this line: {% for speakers in conference.speakers %}

Django Solutions


Solution 1 - Django

You need to call all on the many-to-many field to get an iterable object. Also, the next line should contain the speaker rather than conference.speakers.

{% for speaker in conference.speakers.all %}
        <li>{{ speaker }}</li>
{% endfor %}

Solution 2 - Django

Similar inside pythoncode this would be:

for speaker in conferenece.speakers.all():
  print speaker.FIELDNAME

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoam SmadjaView Question on Stackoverflow
Solution 1 - DjangointerjayView Answer on Stackoverflow
Solution 2 - DjangoRickard ZachrissonView Answer on Stackoverflow