Home > Net >  How to build a table of objects without knowing their attributes?
How to build a table of objects without knowing their attributes?

Time:10-05

I'm trying to build a table dynamically in my django template. I got the column names in my views.py and also got the contents of the table:

    table = tenant_tables.models[table_name].objects.all()
    headers = table.model._meta.get_fields(include_parents=True, include_hidden=False)
    context = {'table': table, 'headers': headers}
    return render(request, template_name=template_name, context=context)

Based on the received data, I want to build a table using a template, but I don't know how to sort through all the attributes of the object

<table
                id="example"
                
                style="width: 100%"
              >
                  <thead>
                    <tr>
                      {% for header in headers %}
                      <th>{{header.verbose_name}}</th>>
                      {% endfor %}
                    </tr>
                  </thead>
                  <tbody>
                  {% for obj in table  %}
                    <tr>
                        <td>{{obj}}</td>
                    </tr>
                  {% endfor %}
                  </tbody>
                  <tfoot>
                    <tr>
                      {% for header in headers %}
                          <th>{{header.verbose_name}}</th>>
                      {% endfor %}
                    </tr>
                  </tfoot>
          </table>

Can I implement this or should I create a view for each model in my application?

CodePudding user response:

Yes, it's possible to implement this. But first you need to implement a custom filter which works like the getattr function in python.

Then you can do this:

...
<tbody>
    {% for obj in table  %}
        <tr>
            {% for header in headers %}
                <td>{{ obj | getattr_filter:header }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
</tbody>
...

The filter should looks something like this:

@register.filter(name='getattr_filter')
def getattr_filter(obj, attribute):
    return getattr(obj, attribute, None)

Check the docs for more details on how to implement a custom template filter.

  • Related