Flask-WTF form has errors during GET request

2019-03-01 17:56发布

问题:

I have a Flask view with a Flask-WTF form. When I load the page in the browser, the form always has errors, even though I haven't submitted it yet. Why does the form have errors before it is submitted?

@app.route('/', methods=['GET', 'POST'])
def index():
    form = ApplicationForm(request.form)

    if form.is_submitted():
        print "Form successfully submitted"

    if form.validate():
        print "valid"

    print(form.errors)  

    if form.validate_on_submit():
        return redirect('index')

    return render_template('index.html', form=form)
127.0.0.1 - - [30/Nov/2016 16:54:12] "GET / HTTP/1.1" 200 -
{'department': [u'Not a valid choice'], 'email': [u'This field is required.'], 'csrf_token': ['CSRF token missing'], 'name': [u'This field is required.'], 'address': [u'This field is required.']}

回答1:

This is a get request, so request.form is empty. You're calling validate unconditionally, so you're validating against empty data. Therefore, everything's invalid. This is why validate_on_submit exists: it doesn't validate for get requests, since they don't have form data.

Remove the if form.validate() block.

form.errors is only populated after validation, so move it below the validate_on_submit block or it will always appear empty.


Also, you don't need to pass request.form, Flask-WTF will automatically pass it if the form is submitted.