简体   繁体   English

Django request.POST 返回空字典

[英]Django request.POST returns an empty dict

code skips the whole if block directly goes to the last else.代码跳过整个 if 块直接转到最后一个 else。 I am using django.forms to get input from the user.我正在使用 django.forms 从用户那里获取输入。 the same thing happens when the method is set to GET.当方法设置为 GET 时会发生同样的事情。 I tried the same with normal HTML forms the same result.我尝试了与正常 HTML forms 相同的结果。 But the weird fact it earlier It was working properly in the initial stages of the project while I was experimenting with my views and models this start causing the error in my project as I cannot get the user input.但奇怪的事实是,它在项目的初始阶段正常工作,而我正在试验我的视图和模型,这开始导致我的项目出现错误,因为我无法获得用户输入。

views.py视图.py

def form(request):
    form = InputForm()
    return render(request, 'classifier/form.html', {'form':form})

def output(request):
    print(request.POST) #  returns empty dict
    if request.method == "POST":
        form = InputForm(request.POST)
        if form.is_valid():
            url = form.cleaned_data['input_url']
            print(url)
            return render(request, 'classifier/output.html', {'url':url})
        else:
            print(form.errors())

    else:
        print("error")
        error = "Oops"

    return render(request, 'classifier/output.html',{'url':error})

form.html表格.html

<form action="{% url 'classifier:output' %}" method="POST">
   {% csrf_token %}
   {% for non_field_error in form.non_field_error %}
      <p class="help is-danger">{{ non_field_error}}</p>
   {% endfor %}
   {{ form }}
   {% for error in form.erros %}
       <p class="help is-danger">{{ error }}</p>
   {% endfor %}
   <div class="text-center">
       <button type="button" class="btn btn-primary" id="btn" value='Save'><a href="{% url 'classifier:output' %}">Submit</a></button>
   </div>
</form>

urls.py网址.py

from django.urls import path
from . import views

app_name = 'classifier'

urlpatterns = [
    path('', views.index, name='index'),
    path('form/',views.form, name='form'),
    path('output/',views.output, name='output'),
]

In your template:在你的模板中:

<div class="text-center">
       <button type="button" class="btn btn-primary" id="btn" value='Save'><a href="{% url 'classifier:output' %}">Submit</a></button>
   </div>

Submit button in reality is link: <a href="{% url 'classifier:output' %}">Submit</a>提交按钮实际上是链接: <a href="{% url 'classifier:output' %}">Submit</a>

so there is a simple link following.所以下面有一个简单的链接。

The corrected part of the code looks like this:代码的更正部分如下所示:

<div class="text-center">
           <button type="submit" class="btn btn-primary" id="btn">Submit</button>
       </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM