What Is the Cause of the Bad Request Error When Submitting Form in Flask Application

What is the cause of the Bad Request Error when submitting form in Flask application?

The solution was simple and uncovered in the comments. As addressed in this question, Form sending error, Flask, and pointed out by Sean Vieira,

...the issue is that Flask raises an HTTP error when it fails to find a
key in the args and form dictionaries. What Flask assumes by default
is that if you are asking for a particular key and it's not there then
something got left out of the request and the entire request is
invalid.

In other words, if only one form element that you request in Python cannot be found in HTML, then the POST request is not valid and the error appears, in my case without any irregularities in the traceback. For me, it was a lack of consistency with spelling: in the HTML, I labeled various form inputs

<input name="question1_field" placeholder="question one">

while in Python, when there was a POST called, I grab a nonexistent form with

request.form['question1']

whereas, to be consistent with my HTML form names, it needed to be

request.form['question1_field']

I hope this helps.

Getting a 400 bad request error while submitting a flask form

Try using request.form.get("name_of_field") instead of just request.form["name_of_field"].

When you use request.form["name_of_field"], flask assumes that they key will always be there. you canavoid this by using the other one, or the try and except trick.

Form sending error, Flask

As @Blubber points out, the issue is that Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key and it's not there then something got left out of the request and the entire request is invalid.

There are two other good ways to deal with your situation:

  1. Use request.form's .get method:

    if request.form.get('add', None) == "Like":
    # Like happened
    elif request.form.get('remove', None) == "Dislike":
    # Dislike happened
  2. Use the same name attribute for both submit elements:

    <input type="submit" name="action" value="Like">
    <input type="submit" name="action" value="Dislike">

    # and in your code
    if request.form["action"] == "Like":
    # etc.


Related Topics



Leave a reply



Submit