I have a flask application where I want to flash different alert messages depending on an action.
here is my first message, where i check if an email matches my regex pattern:
reciver = str(email)
if not re.match(r"[^@]+@[^@]+\.[^@]+", reciver):
flash("Please enter a valid email address", 'error')
return render_template("about.html")
here is the second message, which is displayed if a message is sent successfully:
flash('Message sent succesfully', 'succes')
return render_template("about.html")
here is my HTML code:
<h1 class="mb-5"> Enter your message, and i will get back to you as soon as possible</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success">
<li>{{ message }} </li>
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
how can I make an alert-danger for the first message and an alert-success for the second message, is there some sort of conditional that can be used?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With