python - Form sending error, Flask -


there form 2 <input type="submit">. 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, second(remove)...:

bad request browser(or proxy) sent request server not understand.

how can fix error?

upd:

it pretty simple: request.form returns immutablemultidict:

...  if 'like' in request.form.values():      ... elif 'dislike' in request.form.values():      ... 

as @blubber points out, issue flask raises http error when fails find key in args , form dictionaries. flask assumes default if asking particular key and it's not there got left out of request , entire request invalid.

there 2 other ways deal situation:

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

    if request.form.get('add', none) == "like":     # happened elif request.form.get('remove', none) == "dislike":     # dislike happened 
  2. use same name attribute both submit elements:

    <input type="submit" name="action" value="like"> <input type="submit" name="action" value="dislike">  # , in code if request.form["action"] == "like":     # etc. 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -