3

I have a model that is referenced by a generic ListView, and feeds into a template. Attempts to create a table in the template give me a TypeError: not iterable - what am I doing wrong?

Sample code

Class bookmodel(models.Model):
     Book = models.CharField(max_length=255)
     Author = models.CharField(max_length=255)

Views

Class bookview(generic.ListView):
     model = bookmodel
     template = “books.html”

Which generates an object_list something like:

<Queryset [<bookmodel: Grapes of Wrath >, <bookmodel: I, Robot>]>

The template is laid out as follows:

{% extends ‘base.html’ %}
{% block content %}
<table>
    <thead>
         <tr>
               <th> book </th>
               <th> author </th>
         </tr>
    </thead>
    <tbody>
         {% for object in object_list %}
         <tr>
                {% for field in object %}
                <td> {{ field }} </td>
                {% endfor %}
         </tr>
         {% endfor %}
     </tbody>
</table>
{% endblock %}

But this fails with the aforementioned error.

Tahnoon Pasha
  • 5,848
  • 14
  • 49
  • 75

1 Answers1

0

The linked question kindly suggested by @Karioki in his comment proposed the following code:

def attrs(self):
    for field in self._meta.fields:
        yield field.name, getattr(self, field.name)

The yield function inexplicably didn't work for me in my template either from a view or a template tag:

The following derivative code did:

def get_values(self):
        value_set = [getattr(self, field.name) for field in self._meta.fields]
        return value_set

While this still feels clunky to me, I'm marking it as a straw man answer but am hopeful that there will be another answer that provides a more efficient way to investigate a database record in the template in Django.

Tahnoon Pasha
  • 5,848
  • 14
  • 49
  • 75