70116

Accessing a two dimensional array in Django template

Question:

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

Answer1:

Passing Multi-dimensional arrays to templates in django is not straight forward. I've been working on this problem for a while, so I know your question is old, but for the betterment of django society, here's what I've finally worked out...

users = User.objects.all() games = Game.objects.all() bets = Bet.objects.all() user_bets=[] game_title=[] for i, game in enumerate(games): game_titles = [game.title] game_bets = bets.filter(game=game) for usr in users: user_bet = game_bets.filter(user=usr)[0] user_bets[i][usr.id]=user_bet data = {'game_titles', game_titles 'users', users, 'user_bets': user_bets} return render(request, 'bets.html', data)

You then want to define two template filters, which for ease can live in your views.py

@register.filter def index(List, i): return List[int(i)] @register.filter def entry_num_array(List): return range(len(List))

Then in your template

{% for bet in user_bets %} {{ game_titles|index:forloop.counter0}}: {% for counter in entry|entry_num_array %} {{entry|index:counter}}| {% endfor %} <br> {% endfor %}

Recommend

  • How do references in functions work?
  • Thrust filter by key value
  • Laravel 5.1 Multitenancy setup
  • How to calculate total across columns but one?
  • Why is this button causing my layout to break?
  • Receive custom intent without activity restart
  • How can I count unique terms in a plaintext file case-insensitively?
  • Programmatically Update Linked Named Range of excel object in MS Word (2007)
  • Not able to display correct data in table -AngularJS
  • Accessing Rows In A LINQ Result Without A Foreach Loop?
  • Undefined navigator.push React-native 0.43.4
  • Sesame : how to remove the inference during queries?
  • redirect_to root_url and return unless @user.activated
  • Doctrine/Symfony entity generator and generating entity from one table
  • Elasticsearch script query involving root and nested values
  • cygwin cannot exec 'git-add--interactive' permission denied
  • Django invalid literal for int() with base 10
  • Run multiple queries from 1 SQL file showing result in multiple tables
  • Copy to all folders batch file?
  • wxPython: displaying multiple widgets in same frame
  • error importing numpy
  • Remove final comma from string in vb.net
  • copying resource to sdcard gives a damaged file in android
  • dc-js disable selecting slices on click for pie chart
  • Spring security and special characters
  • Modifying destination and filename of gulp-svg-sprite
  • retrieve vertices with no linked edge in arangodb
  • How to delete a row from a dynamic generate table using jquery?
  • embed rChart in Markdown
  • Linking SubReports Without LinkChild/LinkMaster
  • Bitwise OR returns boolean when one of operands is nil
  • Is there any way to bind data to data.frame by some index?
  • Django query for large number of relationships
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF
  • How to push additional view controllers onto NavigationController but keep the TabBar?