listing objects from ManyToManyField

Noam Smadja picture Noam Smadja · May 3, 2010 · Viewed 40.6k times · Source

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 %}

Answer

interjay picture interjay · May 3, 2010

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 %}