I'm trying to display a page with a form, then add a Player
to the database when the form is submitted. However, I can't view the form because the browser always shows a 400 Bad Request
error. Other posts indicate that this could be because the name of the form input doesn't match the key I get from request.form
, but all my keys match. Why do I get this error?
<form method="post">
{{ form.hidden_tag() }}
<input name="name">
<input name="available">
<input type="submit">
</form>
@app.route('/addplayer', methods=['GET', 'POST'])
def addplayer():
connect('basketball_contracts', host='localhost', port=27017)
n = request.form['name']
a = request.form['available']
post= Post(
name=n,
available=a
)
post.tags = ['test']
post.save()
return render_template('addplayer.html', form=form)
Your view accepts
GET
andPOST
requests.request.form
is only filled out onPOST
. If you try to access a key that doesn't exist, it raises a 400 error. No keys will exist when youGET
the page initially.The common pattern for this is to guard code that requires
request.form
in anif request.method == 'POST'
block. Return a redirect after handling thePOST
request, otherwise return the rendered template.Since you appear to be using Flask-WTF, you can use the form's
validate_on_submit
method instead of checkingmethod
. In that case, you can also access the data through the form instance, and use the form to render the inputs for you.