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:
use
request.form
's.get
method:if request.form.get('add', none) == "like": # happened elif request.form.get('remove', none) == "dislike": # dislike happened
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
Post a Comment