In your python view:
if form.validate_on_submit(): flash(f'Account created for {form.username.data}!', category='success')
Then we display these flash messages in a template file like so:
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}">{{message }}</div> {% endfor %} {% endif %} {% endwith %}
Here with_categories=true
part allows the flashed messages to accept bootstrap classes like ‘success’ that we passed.
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
here ‘Username’ is automatically designated as label for this form field in the form. So in my html for the corresponding form, I can set both label and actual form like so:
<div class="form-group"> {{ form.confirm_password.label(class="form-control-label") }} {{ form.confirm_password(class="form-control form-control-lg") }} </div>
How to display validation errors on form fields
We display form fields like so:
<div class="form-group"> {{ form.email.label(class="form-control-label") }} {{ form.email(class="form-control form-control-lg") }} </div>
Now, if the user entered and email that was not valid, we need to show some feedback message to the user (we call it postback). We do it by using “is-valid” class offered by Bootstrap like so.
<div class="form-group"> {{ form.email.label(class="form-control-label") }} {% if form.email.errors %} {{ form.email(class="form-control form-control-lg is-invalid") }} <div class="invalid-feedback"> {% for error in form.email.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.email(class="form-control form-control-lg") }} {% endif %} </div>
Here, the else block shows the form field when there was no error.