我的Django视图/模板中的这个循环有什么问题?

时间:2009-12-08 00:41:33

标签: django django-templates

我讨厌在这里问,但我很难过,irc的那些人也很难过。

模板不显示我要显示的列表的内容。

单独

{{bet}}也不会显示任何值。我错过了什么?

模板:

{% 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 %}

查看:

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 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))

投注变量的上下文:

'下注':[[1,5,你',你',1.0,1.0,3.0],[2,4,你',你',2.0,2.0,43555.0],[3 ,3,你',你',3.0,3.0,5.0]]

3 个答案:

答案 0 :(得分:4)

模板是指bet中的命名字段,但是你传入了一个数组。

更改append中的choose_bets,如下所示:

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))

所以你现在有一个带有键的词典,你可以从模板中按原样引用。

或者......更改模板以使用您传入的数组。例如,而不是:

<td><div>{{ bet.game_num }}</div></td>

使用:

<td><div>{{ bet.0 }}</div></td>

答案 1 :(得分:1)

{% debug %}标记开始。查看上下文是否包含您认为应该包含的内容。

答案 2 :(得分:0)

为什么不尝试逐个明确地传递每个变量,看看它在什么时候停止工作,而不是使用本地