同一页面中的多个表单,提交时保持数据填充

Multiple forms in the same page, keep data populated when submitting

当我提交一个表单时,我将丢失另一个表单中预填充的数据。我的意思是,要重现问题,请提交 form_1,然后我将丢失 form_2 中的选定数据。所以,这个在提交的时候会被忽略。

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

您可以测试这段代码来检查问题:

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)

我期望的是在提交其他表单后保持预填充的数据仍然可用。

经过进一步调查,我发现问题出在 request.form。

如果我在提交其他表单时在解包之前删除 request.form,那么一切都会按预期进行。不知道还有没有更友好的方式,不过这个对我有用

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