1

I understand how to validate each field and show each error if needed. But how do I show a form error.

What I mean is that the user may enter valid info, but the form might be wrong as a whole.

Example: Form with username and password. Each would have a validator. How can I display an error if the login failed (account doesn't exist or incorrect password)?

I tried raising a ValidationError... but that just raises an error as normal.

def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        if login(username, password):
            return redirect(url_for('dashboard'))
        else:
            raise ValidationError('Invalid login')

    return render_template('login.html', form=form)

1 Answer 1

2

change your raise ValidationError('Invalid login') to flash('Invalid login')
and remember to from flask import flash
then add a field to your 'login.html' to show this message

{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ message }}
</div>
{% endfor %}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh I had forgotten about that. Is that what flash is normally for? It's there any way to send the error through wtforms?
I usually use this way and you can add the field to your base template,so you can use flash everywhere. I don't know how to do this with wtforms.

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.