Multiple forms on one page, keep the data filled in when submitting

When I submit one form, I will lose data pre-filled in the other form. What I mean is, to reproduce the problem, submit form_1, then I will lose the selected data in form_2. Thus, this is ignored when submitting.

test = {'1':True}
form = F(**test) 

      


You can check this code to check the problem:

from flask import Flask, render_template
from flask_bootstrap import Bootstrap

from flask_wtf import Form
from wtforms import SelectField, SubmitField, TextField, BooleanField

app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
Bootstrap(app)

if __name__ == '__main__':
    app.run()

class UserCriteria(Form):
    factor_1_criteria = SelectField('A', choices=[('1', 'Bad'), ('2', 'Mediocre'), ('3', 'Quite good'), ('4', 'Awesome')])
    submit = SubmitField('Update')

def interests():
    class F(Form):
        pass

    setattr(F, 'submit_interests', SubmitField('Submit'))

    interests = [{"id": 1, "industry": 'banks'},{"id": 2, "industry": 'soccer'}]

    for name in interests:
        setattr(F, str(name['id']), BooleanField(name['industry']))

    test = {'1':True}
    form = F(**test)

    return form

@app.route('/', methods=['GET', 'POST'])
def index():
    form_1 = UserCriteria()
    form_2 = interests()

    return render_template("users/profile.html", form_1=form_1, form_2=form_2)

      

What I am expecting is to keep all completed data still available after another form is submitted.

+3


source to share


1 answer


After some further research, I found that the problem was with request.form.

If I remove request.form before unpacking when another form is submitted, then everything works as expected. I don't know if there is an even friendlier way, but this works for me.



if request.form.getlist('submit_criteria'):
      del request.form

      

+1


source







All Articles