'Accessing a two dimensional array in Django template
I am building a betting app where users can bet on different games. I want to show users' bets for different games in a table such as one as below:
game # | user 1 | user 2 | user 3
game 1 | XXXX | XXXX | XXXX
game 2 | XXXX | XXXX | XXXX
game 3 | XXXX | XXXX | XXXX
...
here's my view
users = User.objects.all()
games = Game.objects.all()
bets = Bet.objects.all()
user_bets = [[] for i in range(len(games))]
for i, game in enumerate(games):
game_bets = bets.filter(game=game)
for usr in users:
user_bet = game_bets.filter(user=usr)[0]
user_bets[i].append(user_bet)
data = {'games', games, 'users', users, 'user_bets': user_bets}
return render(request, 'bets.html', data)
But I don't know how to fill in the table using the 2d array user_bets. Any suggestions? Or if I'm doing the whole thing wrong any best practice to pass such data to template in Django?
Cheers
Solution 1:[1]
For those who are looking for accessing a standard 2D array,you can use nested loop. code is below
views.py
content={'f':[[1,2,3,4],[4,5,6,7]]}
return render(request,'index.html',content)
index.html
{% for array in f %}
{% for content in array %}
<h1>{{content}}</h1>
{% endfor %}
{% endfor %}
Solution 2:[2]
For those who are looking for accessing a combination of Lists,Touples, etc. you can programm a nested loop as mentioned above by "The Guardener" and builtins if tags:
some_list={
1:{('a','Answer1'),('b','Answerb')},
2:{'Something':'else'},
3:{'Something':'else'}
}
Template: index.html:
{% for nested_list in some_list %}
{% for list_element in nested_list %}
{% if list_element.0 == 'a' %}
some_list[nested_list[list_element[0]=='a']]]: {{ list_element.1 }} # Answer1
{% endif %}
{% endfor %}
{% endfor %}
I couldn't test this example only parts of it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TheGuardener |
| Solution 2 | Dharman |
