[Django]-I want to represent django model as table in html page with table heading same as django field name. How can I implement this?

5👍

You can do the most important processing part in the view. For example:

def some_view(request):
    model = Car
    field_names = [f.name for f in model._meta.get_fields()]
    data = [[getattr(ins, name) for name in field_names]
            for ins in Model.objects.prefetch_related().all()]
    return render(request, 'some_template.html', {'field_names': field_names, 'data': data})

and as some_template.html:

<table>
    <thead>
    {% for head in field_names %}
       <th>{{ head }}</th>
    {% endfor %}
    </thead>
    <tbody>
    {% for row in data %}
        <tr>
        {% for cell in row %}
            <td>{{ cell }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
    </tbody>
</table>

We thus construct a 2d table for each field name and each model instance. Then we render this data in a HTML template that contains <table> logic.

EDIT: using verbose_name. Since the field names are sometimes a bit cryptic, we can use the verbose_name of the field as well:

def some_view(request):
    model = Car
    field_names = list(model._meta.get_fields())
    titles = [f.verbose_name for f in field_names]
    field_Names = [f.name for f in field_names]
    data = [[getattr(ins, name) for name in field_names]
            for ins in Model.objects.prefetch_related().all()]
    return render(request, 'some_template.html', {'field_names': titles, 'data': data})

Leave a comment