[Answer]-Django DB data to HTML table

1👍

Keep your template code as simple as possible, as RickyA suggests. Do complicated data transformations in your view instead.

Since you have headers on the tops and sides, I would store these in their own lists. Then I would store the actual data in a list of lists. So for instance, in your view code:

student = Student.objects.all()
context['classes'] = [class.name for class in Class.objects.all()]
context['checkPoints'] = range(1, 4)
context['data'] = ... 

(code to flatten checkpoints for each students in to flat list, 
then make list of these lists, don't forget to add the student 
name as the first item in each row)

And in your template, you do something like

<table>
<thead>
<tr>
<th></th>
{% for class in classes %}
<th colspan="3">{{ class }}</th>
{% endfor %}
</tr>
<!-- something similar for checkpoints -->
</thead>
<tbody>
{% for row in data %}
<tr>
{% for item in row %}
{% if not forloop.counter0 %}
<th>{{ item }}</th>
{% else %}
<td>{{ item }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

I think that is valid Django template code. I’ve been using Jinja2 lately, so my apologizes if I threw in a feature that doesn’t work, but it should be okay.

👤acjay

Leave a comment