0

我正在尝试为黑白棋游戏编写一个 django Web 应用程序。我在将新表呈现到网站时遇到问题。

视图.py

def table(request):
    if request.method == "POST":
        coord = request.POST.keys()
        crd = list(coord)[1]
        x = crd.split("_")
        r = int(x[0]) - 1
        c = int(x[1]) - 1
        reversi = ReversiGame()
        grid = draw_grid(reversi)
        ctxt = {"table": grid}
        return render(request, 'table.html', context=ctxt)

模板

{% extends 'base.html' %}
{% block main_content %}
    <div style="text-align: center; width: auto;
    height:auto; margin-right:auto; margin-left:200px;">
    {% for r in table %}
        <div style="float:left">
        {% for c in r %}
             <form action="" method="post">
            {% csrf_token %}
            {% if c == 2 %}
                <input type="submit" style="background: #000000; width:50px; height:50px;
                            color:white;"
                       name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="2">
            {% elif c == 1 %}
                <input type="submit" style="background: #ffffff;  width:50px; height:50px;"
                       name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="1">
            {% else %}
                <input type='submit' style="background: #c1c1c1;  width:50px; height:50px;"
                       name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="o">
            {% endif %}
             </form>
        {% endfor %}
        </div>
    {% endfor %}
    </div>
{% endblock %}

网址.py

urlpatterns = [
    path('', views.HomeView.as_view(), name="home"),
    path('signup/', views.SignUpView.as_view(), name='signup'),
    path('profile/<int:pk>/', views.ProfileView.as_view(), name='profile'),
    path('table/', views.table, name='table')
]

当我尝试在 request.method 中返回 HttpResponse 时,会引发以下错误:The view GameConfiguration.views.table didn't return an HttpResponse object. It returned None instead.

如果我将选项卡向左移动 return render(request, 'table.html', context=ctxt),则无法识别作为新板的 ctxt 变量(它说它在分配之前使用),这意味着我无权访问新绘制的表。

我需要 POST 方法中的 row 和 col 才能翻转棋盘并切换播放器。

我真诚地感谢你的时间!谢谢!

4

1 回答 1

1

您的视图函数仅在request.method == "POST". 当您在浏览器中访问该页面并收到错误The view ... didn't return an HttpResponse object.消息时,那是因为通过浏览器发出的请求具有request.method == "GET".

if您可以通过在语句之外添加返回方法来修复您的视图方法:

def table(request):
    if request.method == "POST":
        # Here is where you capture the POST parameters submitted by the
        # user as part of the request.POST[...] dictionary.
        ...
        return render(request, 'table.html', context=ctxt)

    # When the request.method != "POST", a response still must be returned.
    # I'm guessing that this should return an empty board.
    reversi = ReversiGame()
    grid = draw_grid(reversi)
    return render(request, 'table.html', context={"table": grid})
于 2021-02-16T21:23:56.423 回答