I want to fill the table in a correct way (see the picture). But I can't do it without changing a model or using tables2 app. How I can go through Teams and get 1 player for each team and then go next line for a table? What I have now: Correct and wrong tables
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)
views.py:
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)
templates index.html:
{% 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 %}
Updated (10-30-19): I tried to make another list from current classes in views.py. But I could not do it properly. And now I have made another solution for it. In views.py I added:
context['range_1_7'] = range(1, 7)
It allows me go through for loop 6 times (because 6 is max number of player in a team). And output columns and rows 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 %}
Of course it can seems as so bad solution, but it works. It would be nice to figure out how to use a variable in a variable in django template like this:
{{ player_list.{{ row-1 }}.name }}
In this case it would be possible to remove the multiline IF-statement.