Automatically get name of the column with for loop in django template

Question:

I would like to automatically retrieve the name of the column with a for loop.
If I know the name of the columns I can write the template in this way:

<ul>
{% for co in team %}
    <li>{{ co.name }}</li>
    <li>{{ co.team}}</li>
    <li>{{ co.sport}}</li>
{% endfor %}
</ul>

But in my present case, I do not know the names of the columns of my table. How can I display them?

Thank you

Asked By: Bak

||

Answers:

You can obtain the fields of a model with:

fields = Model._meta.get_fields()

This is a tuple of Field [GitHub] objects. These Field objects have a name attribute, so we can obtain the field names with:

from operator import attrgetter

field_names = map(attrgetter('name'), Model._meta.get_fields())

In case we do not know what the model is, we can obtain a reference to the model of a model instance with type(..):

fields = type(some_instance)._meta.get_fields()

All this logic however does not really belong in the Django template, but in the view (by design, Django templates are a bit restrictive to prevent writing business logic in the template). We can thus pass a list of field names to the template:

def some_view(request):
    teams = Team.objects.all()
    field_names = [f.name for f in Team._meta.get_fields()]
    return render(request, 'some_template.html',
        {'teams': teams, 'field_names': field_names}
    )

If you however want to print the values of these teams, then this will still not work, since we can not easily get an arbitrary attribute in a template. Then we can again shift some processing to the view:

from operator import attregetter

def some_view(request):
    teams = Team.objects.all()
    field_names = [f.name for f in Team._meta.get_fields()]
    atgetters = [attrgetter(fn) for fn in field_names]
    rows = [[ag(team) for ag in atgetters] for team in teams]
    return render(request, 'some_template.html',
        {'teams': teams, 'field_names': field_names, 'data': data}
    )

So here data is a list containing lists, such that data[i][j] contains the value for a field with name field_name[j] for teams[i].

Answered By: Willem Van Onsem
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.