What is wrong with this loop in my Django view/template?
I hate to ask here but I am stumped and so were the guys in irc.
The template does not display the contents of the list I am trying to display.
{{ bet }} alone also displays no values. What am I missing?
Template:
{% for bet in bets %}
<tr>
<td><div>{{ bet.game_num }}</div></td>
<td><div>{{ bet.home_team }}</div></td>
<td><div>{{ bet.home_odds }}</div></td>
<td><div id="home-odds-checkbox"><input type="checkbox"></div></td>
<td><div>{{ bet.visiting_team }}</div></td>
<td><div>{{ bet.visiting_odds }}</div></td>
<td><div id="visiting-odds-checkbox"><input type="checkbox"></div></td>
<td><div>{{ bet.tie_odds }}</div></td>
<td><div id="tie-odds-checkbox"><input type="checkbox"></div></td>
</tr>
{% endfor %}
View:
def choose_bets(request):
# Should be a post to get to this page
num_games = int(request.POST['games']) + 1
# Fill BetData with teams and odds
bets = []
for x in range(1, num_games):
try:
league_id = int(request.POST[str(x) + '-league'])
game_num = int(request.POST[str(x) + '-game_num'])
home_team = request.POST[str(x) + '-home_team']
visiting_team = request.POST[str(x) + '-visiting_team']
home_odds = float(request.POST[str(x) + '-home_odds'])
visiting_odds = float(request.POST[str(x) + '-visiting_odds'])
tie_odds = float(request.POST[str(x) + '-tie_odds'])
skip_game = False
except ValueError:
league_id,game_num,home_odds,visiting_odds,tie_odds = 0,0,0,0,0 # bad fix
home_team,visiting_team = '',''
skip_game = True # Do not 开发者_JAVA百科include entry in calculation
finally:
bets.append([game_num, league_id, home_team, visiting_team, home_odds, visiting_odds, tie_odds, skip_game])
return render_to_response('choose_bets.html', locals(), context_instance=RequestContext(request))
Context of bet variable:
'bets': [[1, 5, u'', u'', 1.0, 1.0, 3.0], [2, 4, u'', u'', 2.0, 2.0, 43555.0], [3, 3, u'', u'', 3.0, 3.0, 5.0]]
The template is referring to named fields in bet
, but you passed in an array.
Either change your append
in choose_bets
like this:
bets.append(dict(game_num=game_num, league_id=league_id, home_team=home_team, visiting_team=visiting_team, home_odds=home_odds, visiting_odds=visiting_odds, tie_odds=tie_odds, skip_game=skip_game))
So you now have a dict with keys you can reference as-is from your template.
Or... change the template to use the array you are passing in. For example instead of:
<td><div>{{ bet.game_num }}</div></td>
Use:
<td><div>{{ bet.0 }}</div></td>
Start with the {% debug %} tag. See if the context contains what you think it should.
Why don't you try passing each variable through explicitly one by one and seeing at what point it stops working, rather than using locals
精彩评论