3

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
0

2 Answers 2

10

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))
Sign up to request clarification or add additional context in comments.

Comments

-1

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

  form = MyForm(data=data)

1 Comment

I've tried data= and didn't work. 'name' was never set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.