Flash Messages in Flask: How to Display Temporary Alerts Step by Step
Content Index
- What are flash messages in Flask and what are they for?
- How to use the flash() function in Flask
- Displaying messages in templates with get_flashed_messages()
- Categories of flash messages in Flask
- Complete example: CRUD with flash messages
- Customizing the appearance of flash messages
- Common errors and how to solve them
- Frequently asked questions about flash messages in Flask
- Conclusion
Displaying confirmation messages based on the operation performed is a regular task; in many other technologies, including Flash, there are flash messages, which are those that only last one request, therefore, they are ideal for indicating whether a record is created, updated, or deleted correctly or simply a system error or other message.
Flash messages in Flask are a very useful tool for displaying temporary alerts, either to confirm an operation or report an error. In my experience, this pattern is key to improving user interaction without complicating the code: a message is shown once and disappears when the page is reloaded or changed.
What are flash messages in Flask and what are they for?
In Flask, a flash message is a notification that is temporarily saved in the user's session and is displayed in the next rendered view. After being displayed, it disappears automatically.
They are ideal for operations such as:
- Creating, updating, or deleting records.
- Displaying success, warning, or error messages.
- Informing about form validations.
For this, we have the function called flash() which receives the corresponding message as an argument:
my_app\tasks\controllers.py
from flask import flash
***
@taskRoute.route('/update/<int:id>', methods=['GET','POST'])
def update(id:int):
***
if form.validate_on_submit():
operations.update(form.name.data, form.category.data)
flash('The registry has been updated successfully')
return render_template('dashboard/task/update.html', form=form, formTag=formTag, formTagDelete=forms.TaskTagRemove() ,task=task, id=id)Now, with our Flask app using Jinja2 to display the message, we do it from the templates using the get_flashed_messages() function which returns a list of the established messages (we can establish more than one message per request) and we iterate over them:
my_app\templates\dashboard\master.html
***
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
***Since flash-type messages can be used in any situation and not just in the previous CRUD operations, it is a good idea to place it in the template, so that once established from the controller, they can be displayed regardless of the controller that defines them.
How to use the flash() function in Flask
The flash() function receives the message to display as the first argument. Flask stores it in the session and keeps it available until the next template is rendered. You can also add a second parameter to categorize the message (for example, "info", "error", "success").
flash('record updated', 'info') This is very useful when you want to apply different visual styles according to the type of message. In my case, defining categories has allowed me to show blue alerts for information and red alerts for errors.
Displaying messages in templates with get_flashed_messages()
To display flash messages, Flask offers us the get_flashed_messages() function, which returns a list of all messages stored in the session.
In my project, I usually place it in the base template (master.html) so that messages appear automatically in all views:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}This way I avoid repeating the block in each template, and any controller that uses flash() will automatically display its message. It is one of the practices that most simplifies code maintenance.
Categories of flash messages in Flask
It is also possible to define categories in the messages, this is useful if you want to place a different design depending on the type of message, for example, if the message is informative, we place a blue container:
Alert message for information categories
Or if it is an error, a red color:
Alert message for error categories
Among other possible adaptations; for this, we define a second parameter to the flash() function that corresponds to the category:
flash('The registry has been updated successfully', 'info')
flash('Operación completada con éxito', 'success')
flash('Error al actualizar el registro', 'error')And from the template, we can filter by category:
{% with infos = get_flashed_messages(category_filter=["info"]) %}
{% if errors %}
{%- for msg in infos %}
***Or we can indicate that when obtaining the list of flash messages, it returns the category in a tuple:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for message in messages %}
***And we will have the category as part of the message:
('info', 'The registry has been updated successfully') In my case, I usually associate each category with a different color using CSS classes or Bootstrap, Tailwind, or similar alerts.
| Category | Suggested Color | Typical Use |
|---|---|---|
| success | Green | Successful operation |
| info | Blue | General information |
| warning | Yellow | Warnings |
| error | Red | Errors or failures |
Complete example: CRUD with flash messages
Suppose you have a Flask application that manages tasks. You can use flash messages for all CRUD operations:
@taskRoute.route('/create', methods=['POST'])
def create():
if form.validate_on_submit():
operations.create(form.data)
flash('Tarea creada correctamente', 'success')
return redirect(url_for('dashboard'))
flash('Error al crear la tarea', 'error')
return render_template('task/create.html', form=form)In this way, when redirecting to the dashboard view, Flask keeps the message in the session and displays it only once.
Customizing the appearance of flash messages
You can integrate the messages with frameworks like Bootstrap or Tailwind to improve their appearance.
For example, with Bootstrap 5:
{% for category, message in get_flashed_messages(with_categories=true) %}
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}I usually use this format because it looks good, is accessible and disappears easily without the need for additional JavaScript.
Common errors and how to solve them
- The flash message is not displayed.
→ Make sure to includeget_flashed_messages()in the template rendered afterflash(). - The message disappears after a redirect.
→ Flask removes messages once they are displayed. If you redirect before rendering, make sure you useredirect()andurl_for()correctly. - Duplicate messages are displayed.
→ Check thatget_flashed_messages()is only invoked once per load.
Frequently asked questions about flash messages in Flask
Can I display multiple messages in the same view?
Yes. Flask allows multiple flash() calls per request, and get_flashed_messages() returns them all in a list.
How to filter messages by category?
You can use category_filter:
{% with infos = get_flashed_messages(category_filter=["info"]) %} Can flash messages be translated or internationalized?
Absolutely. If you use Flask-Babel, you can wrap the texts in _('message') and they will be translated automatically.
Conclusion
Flash messages in Flask are a simple and powerful way to communicate the status of an action to the user. Since I started using them in my projects, my alert flow is cleaner, more consistent, and easier to maintain.
If you combine them with categories and visual styles, you will be able to offer a clearer and more professional experience in your Flask applications.
Next step, learn how to use a relative of flash messages, such as the session in Flask.
I agree to receive announcements of interest about this Blog.
In Flash, there are flash messages, which are those that only last one on request, we are going to know how to use them.