Search code examples
pythonflaskwtformsflask-wtforms

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

Solution

  • 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))