Form sending error, Flask

PythonFormsFlask

Python Problem Overview


There is form with two <input type="submit">. But when i'm sending it, second submit causes error.

layout:

<form action="{{ url_for('index') }}" method="post">
    <input type="submit" name="add" value="Like">
    <input type="submit" name="remove" value="Dislike">
</form>

main.py:

...
if request.method == 'POST':
    if request.form['add']:
        return redirect(url_for('index'))
    elif request.form['remove']:
        return redirect(url_for('index'))
...

First submit(add) works well, but second(remove)...:

> Bad Request The browser(or proxy) sent a request that this server could not understand.

How can i fix this error?

UPD:

It was pretty simple: request.form returns ImmutableMultiDict:

... 
if 'Like' in request.form.values():
     ...
elif 'Dislike' in request.form.values():
     ...

Python Solutions


Solution 1 - Python

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.
    

Solution 2 - Python

You should be checking whether or not the 'add' and 'remove' keys are in the request.form dict.

if request.method == 'POST':
    if 'add' in request.form:
        return redirect(url_for('index'))
    elif 'remove' in request.form:
        return redirect(url_for('index'))

When you click Like it doesn't fail because the first condition is met, and hence the second is never checked. But if the Dislike button is clicked, that first condition will thrown a KeyError exception because request.form doesn't contain a key named 'add'.

Solution 3 - Python

Instead of <input type="submit"> Use <button type="submit">. I have the same error as you and tried soo many solution but none of that work

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDmitrijs ZubriksView Question on Stackoverflow
Solution 1 - PythonSean VieiraView Answer on Stackoverflow
Solution 2 - PythonBlubberView Answer on Stackoverflow
Solution 3 - PythonMEET SHAHView Answer on Stackoverflow