简体   繁体   中英

Populate WTForms form from dictionary when using Flask-WTF

I have a Flask-WTF form that needs to be populated from a dictionary, which I pass in as **kwargs . The form is used in a Flask route that is accessed using the POST method. The form doesn't validate, and the field's value is None . How can I pass a dictionary of data to my form and then validate it?

@app.route('/submit', methods=['POST'])
def submit():
    data = {'name': 'eee'}
    form = MyForm(**data)
    print(form.validate())  # False, name is required
    print(form.name.data)  # None

Flask-WTF automatically passes request.form when the route is posted to, if no data is passed explicitly. You need to pass your data, as a MultiDict , to prevent the automatic behavior. Passing obj , data , or **kwargs , only sets the defaults, which are only used if no real data is passed to the form.

form = MyForm(MultiDict(data))

You have to use data parameter for the constructor. You can also check the documentation

  form = MyForm(data=data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM