Bill Noble
Bill Noble

Reputation: 6744

Show manytomany field in Django list view

I am trying to show the values of a manytomany field called teachers in a Django ListView.

At present my model looks like this:

class Classform(models.Model):

    # Fields
    name = models.CharField(max_length=255)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

    # Relationship Fields
    school = models.ForeignKey('eduly.School', default=1)
    teachers = models.ManyToManyField('eduly.Teacher', )

My ListView looks like this:

class ClassformListView(GroupRequiredMixin, ListView):
    model = Classform
    group_required = [u"school_admin"]
    login_url = "/login/"
    raise_exception = True

And my template for the list view looks like this:

<tr>
<td>{{object.pk}}</td>
<td><a href="{{object.get_absolute_url}}">{{object}}</a></td>
<td>{{ object.name }}</td>
<td>{{ object.teachers }}</td>
<td>{{ object.created }}</td>
<td>{{ object.last_updated }}</td>
</tr>

When this code runs the displayed value for object.teachers is appname.Teacher.None

I have noticed that Django has created a table called appname_classform and also a table called 'appname_classform_teachers' (presumably for the manytomany field) but I am not sure how I need to change object.teachers to get the name of the teachers. The 'appname_classform_teachers' contains valid entries for teachers in the app name_teachers table.

Upvotes: 2

Views: 3170

Answers (1)

Ian Kirkpatrick
Ian Kirkpatrick

Reputation: 1960

Use object.teachers.all instead to get the actual queryset.

-- EDIT -- To render these in a custom way:

{% for objs_teacher in object.teachers.all %}
    <p>{{ objs_teacher.first_name }}</p>
    <p>{{ objs_teacher.last_name }}</p>
    ...
{% endfor %}

You can access the indevidual fields in the loop to make it look how you want.

Upvotes: 5

Related Questions