Skip to content Skip to sidebar Skip to footer

Sqlalchemy/wtforms Update Issue - 400 Bad Request

What I'm trying to do is, once the user submits all the results I want it to update the Fixture_prediction model according to my filters. Although what I get is 400 bad request. Th

Solution 1:

The problem is that there is no field fixture_id in request.form. This results in a KeyError being raised by the underlying MultiDict, which is translated into a 400 by Flask.

The reason there is no fixture_id is because you are using the field enclosures FieldList and FormField both of which alter the names you provide to WTForms to avoid collisions.

The fix is to simply use the form instance that you have to access the data (as WTForms has already mapped it for you):

# in your else clausefor prediction in form.predictions:store=Fixture_prediction.query\.filter_by(user_id=user_id)\.filter_by(fixture_id=prediction.fixture_id.data)# etc. 

Solution 2:

According to the flask docs, a 400 occurs when:

What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.

It sounds like the wtform is accessing a key that is not in the multidict, raising a keyerror. To test this, wrap the validate call with a try/except. (I think, I'd assume this is where the keyerror occurs). If you catch the exception, you'll have your answer.

Post a Comment for "Sqlalchemy/wtforms Update Issue - 400 Bad Request"