How to flash success and danger with different messages in flask.
You can use the following pattern to specify the category
parameter of the flash
function.
:param category: the category for the message. The following values are recommended:
'message'
for any kind of message,'error'
for errors,'info'
for information messages and'warning'
for warnings. However any kind of string can be used as category.
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert {{ category }}"> {{ message|capitalize }} </div>
{% endfor %}
{% endif %}
{% endwith %}
By putting category
in the class attribute, you can associate special colors with some css rules like :
.alert.success {
background-color: green;
}
.alert.error {
background-color: red;
}
flash('Message sent successfully', 'success')
flash("Please enter a valid email address", 'error')
These calls will generate:
<div class="alert success"> Message sent successfully </div>
<div class="alert error"> Please enter a valid email address </div>
Official documentation : http://flask.pocoo.org/docs/1.0/patterns/flashing/#flashing-with-categories
With flask 1.0.2 this similar but slightly different approach worked for me - slightly simpler I think:
flash('This is an error message in red', 'danger')
flash('This is an informational message in blue', 'info')
In Flask HTML template:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}" role="alert"> {{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
This way I didn't need to define any CSS and just used what was already in the default Flask distribution.