ovg
ovg

Reputation: 1546

Flask wtform errors rather than field errors

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)

Upvotes: 1

Views: 2614

Answers (1)

hukaixuan
hukaixuan

Reputation: 376

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 %}

Upvotes: 2

Related Questions