【问题标题】:Post method not working, only get request发布方法不起作用,仅获取请求
【发布时间】:2022-07-25 17:59:23
【问题描述】:

我有这样的表格:

<form method=\"post\">
 {% csrf_token %}
 <div class=\"mb-3\">
     <input type=\"hidden\" class=\"form-control\" id=\"url\" name=\"delete-id\" value=\"{{ url.id }}\">
 </div>
 <div class=\"mb-3\">
     <button type=\"submit\" class=\"btn btn-primary mb-3\">Delete</button>
 </div>
</form>

此表单嵌入在表格的单元格中。 我在表单中提出了一个发布请求,但是当我测试 request.method 时,它总是给我 GET 答案。

if request.method == \'post\':
    Url.objects.get(id=request.POST.get[\'delete-id\']).delete()

这里 request.method 总是 GET ,我不明白为什么。

这是我的整个功能:

@login_required
def website(request, website_id):

    if request.method == \'POST\':
        Url.objects.get(id=request.GET[\'delete-id\']).delete()

    customer_id = request.session.get(\'customer_id\')
    context = {
        \'website\': Website.objects.get(id=website_id, customer__id=customer_id)
    }
    return render(request, \'main/website.html\', context)
  • 即使在提交表单后,您是否将 request.method 作为 GET ?
  • 是的,即使按下删除按钮,我也会得到 GET
  • 如果你得到它为GET,那么你有问题&lt;form method=\"post\"&gt; - 也许你只有&lt;form&gt; 而没有method - 在网络浏览器中使用Ctr+U 来查看页面的源代码。也许您使用错误的模板生成页面。
  • 如果可以从您的视图和模板文件中添加更多内容
  • 页面源未更新。我在 docker 容器上运行。方法是在页面源中删除。这就是为什么它不起作用。

标签: python django html-table csrf delete-row


【解决方案1】:

将您的 if request.method == 'post': 替换为 if request.method == 'POST':。事实上,它永远不会是post,因为它区分大小写。

【讨论】:

  • 即使我以这种方式检查,当我调试该方法时仍然是 GET..
  • 我试过你的代码,我得到了一个 post 方法,你确定你之前没有重定向或类似的东西吗?
  • 这对我来说听起来不错,我不明白你为什么在这里得到一个 GET 方法
  • 我发布了整个功能......我没有使用任何重定向
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2014-08-13
相关资源
最近更新 更多