有没有办法在 Django 的 if 语句中呈现请求?

问题描述

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

views.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 %}

urls.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,context=ctxt) 的左侧,则无法识别 ctxt 变量,即新的板(它说它在赋值之前使用),这意味着我没有访问权限到新绘制的表格。

我需要 POST 方法中的行和列,以便翻转棋盘和切换播放器。

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

解决方法

您的视图函数仅在 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,context={"table": grid})