【问题标题】:Django using pk like int in the view functionDjango 在视图函数中使用 pk like int
【发布时间】:2017-04-27 23:45:30
【问题描述】:

我正在尝试制作一个异步多人游戏。 我的想法是在玩家之间共享一个模板('play_game.html')。 因此,当玩家 1 轮到时,会出现一个底部,当他按下它时,函数 play_game 会收到一个请求和一个 1,有了这个,它会在轮次中添加一个 1,所以它会渲染 play_game.hmtl 与下回合玩。问题: 游戏功能总是得到一个。如果我在浏览器中按 F5 但不按底部,则该值仍然为 1。我不知道。

这是代码:

这是函数

@login_required
def play_game(request, flag):
    current_user = User.objects.get(user=request.user.id)
    game = current_user.game
    if int(flag) == 1:
        if game.turn < game.players_total:
            game.turn = game.turn + 1
        else:
            game.turn = 1
        game.save()
    turn = game.turn
    context = {
        'current_user' : current_user,
        'turn' : turn
    }
return render(request,'play_game.html', context) 

这是模板 play_game.html

 {% extends 'base.html' %}
 {% load staticfiles %}

 {% block content %}
 {% if current_user.turn == turn %}
 <p> your turn <p/>
 <li><a href="{% url 'play_game' flag=1 %}"> Move </a></li>
 {% endif %}
 {% endblock %}

这是网址:

 url(r'^game_list/join_to_game/play_game/(?P<flag>[0-9]+)/$', views.play_game, name='play_game'),

换句话说,问题是标志总是一。 我能做什么?

谢谢

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    这一行的问题,你总是将 flag 设置为 1:

    <a href="{% url 'play_game' flag=1 %}">
    

    尝试将标志作为上下文变量传递给模板:

    context = {
        'current_user' : current_user,
        'turn' : turn,
        'flag' : flag 
    }
    

    然后在模板内部每次使用添加过滤器单击按钮时都会增加其值:

    <li><a href="{% url 'play_game' flag=flag|add:'1' %}"> Move </a></li>
    

    【讨论】:

    • 谢谢,但它不起作用:/。我会尝试使用简单的 Post 方法
    猜你喜欢
    • 2022-10-14
    • 2011-08-25
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多