#python #django #django-views #httpresponse #reversi
#python #django #django-представления #httpresponse #реверси
Вопрос:
Я пытаюсь написать веб-приложение django для Reversi Game. У меня проблема с отображением новой таблицы на веб-сайте.
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')
]
Когда я пытаюсь вернуть HttpResponse в request.method, возникает следующая ошибка: The view GameConfiguration.views.table didn't return an HttpResponse object. It returned None instead.
Если я перемещаю вкладку влево return render(request, 'table.html', context=ctxt)
, то переменная ctxt, которая является новой платой, не распознается (в ней говорится, что она используется перед назначением), что означает, что у меня нет доступа к недавно созданной таблице.
Мне нужны строка и столбец из метода POST, чтобы перевернуть доску и переключить игрока.
Я искренне ценю ваше время! Спасибо!
Комментарии:
1. Это потому, что вы сделали запрос GET.
2. убедитесь, что вы также обрабатываете запросы GET или просто помещаете обычный рендеринг возврата в конец представления для других запросов
3. Я все исправил. Большое вам спасибо! Мне нужно уделять больше внимания деталям. ! Я очень ценю ваше время!
Ответ №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})
Комментарии:
1. Спасибо, Дэймон! Я исправил это! Я не обратил внимания на этот аспект! Я ценю ваше время! Всего наилучшего!