Populate WTForms form from dictionary when using Flask-WTF

Issue

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

Answered By – davidism

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published