How to display a list of objects containing many-to-many relations in Django template?

Viewed 32981

I have the following models:

class Tag(models.Model):
  name = models.CharField(max_length=20)

class Entry(models.Model):
  title = models.CharField(max_length=100)
  date = models.DateField()
  tags = models.ManyToManyField(Tag)

In a view I create a list of Entry object and want to show the elements in the template:

   {% for entry in entries %}
     {{ entry.title }}
     {{ entry.date }}
   <!--  {% for tag in entry.tags %} {{ tag }} {% endfor %} -->
   {% endfor %}

And with this template code it generates the following TemplateSyntaxError pointing to the template's first line (for tag):

Caught TypeError while rendering: 'ManyRelatedManager' object is not iterable

The entries variable is a list:

entries = Entry.objects.filter(user=user_id)
entries = list(entries)
entries.sort(key=lambda x: x.id, reverse=False)

Do you know what can be the problem here and how to resolve this issue?

I'm new to Django, so any suggestions how to debug the templates may be helpful.

Update

I get the same error even with this template:

{% for entry in entries.all %}
<!-- everything is commented out here -->
{% endfor %}
4 Answers
Related