python - SQLalchemy/wtforms update issue - 400 bad request -
what i'm trying is, once user submits results want update fixture_prediction model according filters. although 400 bad request. log doesnt tell me enough know whats going wrong. ideas?
i think tuple data submitted through form...
the form displays fine when submit form goes straight bad request.
my error
bad request browser (or proxy) sent request server not understand.
what have currently:
views
@app.route('/predictor/',methods=['get','post']) @login_required def predictions(): user_id = g.user.id # retrieve predictions prediction= db.session.query(fixture_prediction,\ fixture_prediction.fixture_id,fixture.stage,\ fixture.home_team,fixture_prediction.home_score,\ fixture_prediction.away_score,fixture.away_team)\ .outerjoin(fixture,fixture.id==fixture_prediction.fixture_id)\ .outerjoin(user,fixture_prediction.user_id == user.id)\ .filter(fixture_prediction.fixture_id==fixture.id)\ .filter(fixture_prediction.user_id==user_id).all() data = {'predictions': prediction} form = predictionlistform(data=multidict(data)) if request.method == 'post': if form.validate() == false: flash('a score missing, please fill in predictions') render_template('predictor.html', form=form) else: #for pred in prediction: store=fixture_prediction.query\ .filter_by(user_id=user_id)\ .filter_by(fixture_id=request.form['fixture_id'])\ .update({'home_score':request.form['home_score']\ ,'away_score':request.form['away_score']}) db.session.commit() flash('prediction added') return redirect(url_for("predictions")) # display current predictions elif request.method == 'get': return render_template('predictor.html', form=form)
template
{% extends "base.html" %} {% block content %} <h1>predictions</h1> <p></p> <p>please make predictions here</p> <form action='' method='post'> {{form.predictions()}} <p><input type="submit" value="submit predictions"></p> </form> {% endblock %}
forms
class predictionform(wtform): fixture_id = fields.integerfield(validators=[validators.required()]) stage = fields.textfield(validators=[validators.required()]) home_team = fields.textfield(validators=[validators.required()]) home_score = fields.integerfield(validators=[validators.required()]) away_score = fields.integerfield(validators=[validators.required()]) away_team = fields.textfield(validators=[validators.required()]) class predictionlistform(wtform): predictions = fieldlist(formfield(predictionform))
the problem there no field fixture_id
in request.form
. results in keyerror
being raised underlying multidict, translated 400 flask.
the reason there no fixture_id
because using field enclosures fieldlist
, formfield
both of alter names provide wtforms avoid collisions.
the fix use form
instance have access data (as wtforms has mapped you):
# in else clause prediction in form.predictions: store = fixture_prediction.query \ .filter_by(user_id=user_id) \ .filter_by(fixture_id=prediction.fixture_id.data) # etc.
Comments
Post a Comment