Answer the question
In order to leave comments, you need to log in
How to correctly populate a table with data in Django Template by columns?
models.py:
from django.db import models
class Server(models.Model):
name = models.CharField(max_length=16)
url = models.CharField(max_length=64)
class Team(models.Model):
server = models.ForeignKey(Server, on_delete=models.CASCADE)
name = models.CharField(max_length=16)
n_players = models.IntegerField(null=True)
class Player(models.Model):
server = models.ForeignKey(Server, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
name = models.CharField(max_length=16, null=True)
highlight = models.BooleanField(default=False)
from django.shortcuts import render
from .models import Server, Team
def index(request):
server_list = Server.objects.order_by('name')[:3]
context = {'server_list': server_list}
return render(request, 'monitor/index.html', context)
{% for server in server_list %}
<h2>{{ server.name }}</h2>
<table>
<tr>
{% for team in server.team_set.all %}
<th>
<b>{{ team }}</b>
</th>
{% endfor %}
</tr>
{% for team in server.team_set.all %}
<tr>
{% for player in team.player_set.all %}
<td>{{ player }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endfor %}
Answer the question
In order to leave comments, you need to log in
the fastest way: output each command in a line, and then transpose the table https://stackoverflow.com/a/40213981
you can instead put players in lists in the view.
I tried to convert the set into a list in views.py . But somehow it didn't work out.
At the moment I decided differently.
In views.py added
This allows you to loop through the template 6 times (because there is a maximum of 6 players in each team).
And the row/column output is now like this ( templates ):
{% for row in range_1_7 %}
<tr>
{% for team in server.team_set.all %}
{% with team.player_set.all as player_list %}
<td>
{% if row == 1 %}
{{ player_list.0.name }}
{% elif row == 2 %}
{{ player_list.1.name }}
{% elif row == 3 %}
{{ player_list.2.name }}
{% elif row == 4 %}
{{ player_list.3.name }}
{% elif row == 5 %}
{{ player_list.4.name }}
{% elif row == 6 %}
{{ player_list.5.name }}
{% endif %}
</td>
{% endwith %}
{% endfor %}
</tr>
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question