我有一个模板页面,它遍历我的模型对象并列出每个对象。我的模板名为 user_page.html,下面是列出项目的代码:
<h3>List of your games</h3>
{% if games %}
<ul>
{% for i in games %}
<li>Game</li>
{% endfor %}
</ul>
{% else %}
You have no games.
{% endif %}
每当我访问 user_page.html 时,我都会不断收到消息“你没有游戏”,但我知道我有 Game 对象,因为我在控制台中键入 Game.objects.all() 时会看到它们。到目前为止,这是我在 views.py 中的代码:
@login_required
def create_game(request):
game = Game(creator=request.user)
game.save()
variables = RequestContext(request, {
'game': game,
'board': game.get_set_board()
})
return render_to_response('battleship/create_game.html', variables)
@login_required
def list_games(request):
games_list = Game.objects.get_by_user(request.user)
variables = RequestContext(request, {
'games': games_list
})
return render_to_response('battleship/user_page.html', variables)
这是我的游戏模型的代码:
class Game(models.Model):
creator = models.ForeignKey(User, related_name='creator_set')
def get_set_board(self):
board = Board()
return board
def get_target_board(self):
board = Board()
return board
有任何想法吗?提前致谢!