flask form.validate_on_submit() fails using wtforms
You call form.validate()
everytime someone visits '/'
. When the request is a GET, there is no form data causing validation to fail. You only want to try to validate the form when the request is a POST.
One way to do that is to check the request's method.
if request.method == 'POST': if form.validate(): session['dataserver'] = ds = form.dataserver.data return redirect(url_for('login')) else: flash('Failed validation')
Another common way to do this is with validate_on_submit
. It handles checking for POSTs as well as validating the form.
if form.validate_on_submit(): session['dataserver'] = ds = form.dataserver.data return redirect(url_for('login'))
Here you'd lose your ability to flash your 'validation failed'
message. That may be acceptable, though, because you can check for form errors in your template.
{% if form.errors %} failed validation{% endif %}
UPDATE
If you want to see the errors (which you may not), you can print them in the template instead of the generic "failed validation" message.
{% if form.errors %} {{ form.errors }}{% endif %}