简体   繁体   中英

Django request.POST returns an empty dict

code skips the whole if block directly goes to the last else. I am using django.forms to get input from the user. the same thing happens when the method is set to GET. I tried the same with normal HTML forms the same result. 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

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

<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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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