【发布时间】:2016-06-04 15:06:28
【问题描述】:
我无法确定问题出在哪里。
本质上,我正在尝试通过渲染将上下文(映射到游戏对象列表的命名键的字典)传递给 html sn-p。列表中的每个游戏都属于具有单个字符状态字段的 Game 类。我在游戏列表上有一个“for”循环所以我试图使用“if”标签来访问状态并相应地显示一条消息。渲染sn-p时出现问题,给我报错:TemplateSyntaxError at /user/home
Could not parse the remainder: '==' from 'game.status=='
我相信这与尝试访问游戏的状态属性有关。 这是该类的一些代码:
class Game(models.Model):
first_player = models.ForeignKey(User, related_name="games_first_player")
second_player = models.ForeignKey(User, related_name="games_second_player")
next_to_move = models.ForeignKey(User, related_name="games_to_move")
start_time = models.DateTimeField(auto_now_add=True)
last_active = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, default="A", choices=GAME_STATUS_CHOICES)
objects = GamesManager()
这是生成列表并将其传递给渲染的视图
def home(request):
my_games = Game.objects.games_for_user(request.user)
active_games = my_games.filter(status="A")
finished_games = my_games.exclude(status="A")
waiting_games = active_games.filter(next_to_move=request.user)
other_games = active_games.exclude(next_to_move=request.user)
context = Context({'other_games': other_games,
'waiting_games': waiting_games,
'finished_games': finished_games})
return render(request, 'user/home.html', context)
这里是 user/home.html 的相关部分
<h3> Here is your current overview:</h3>
{% block content %}
<div class="well col-md-6">
{% include "tictactoe/game_list_snippet.html" with header="Games Awaiting Your Move" games_list=waiting_games %}
{% include "tictactoe/game_list_snippet.html" with header="Waiting Games" games_list=other_games %}
{% include "tictactoe/game_list_snippet.html" with header="Finished Games" games_list=finished_games %}
</div>
{% endblock content %}
最后是sn-p
<div class="list-group">
{% for game in games_list %}
<a class="list-group-item" href="#">
{{ game }}:
{% if game.status == "A" %}
{% if game.next_to_move == user %}Your Turn{% else %} Waiting for opponents turn {% endif %}
{% elif game.status== "D" %}
Draw
{% elif game.status== "F" and user == game.first_player %}
You Won!
{% elif game.status== "S" and user == game.second_player %}
You Won!
{% else %}
You Lost.
{% endif %}
<span class='badge'>{{game.move_set_count}}</span></a>
{% empty %}
<span class="list-group-item">No Games Available.</span>
{% endfor %}
为了全面披露,我通过 Pluralsight 上的 django 课程获得了大部分代码。不幸的是,他使用的是 django 1.5,而我使用的是 1.9,这不是第一次出现弃用/添加/更改问题,但这是我第一次无法在文档或此处找到答案.我很确定问题出在 {% if %} 标签中的模板逻辑中,因为如果我把它删掉,{% for %} 循环就会起作用,并且页面会显示正确的游戏列表。我意识到这篇文章很长,我只想说这里的任何/所有帮助将不胜感激。提前致谢!
【问题讨论】: