Flash Messages
Flash messages are those little notifications that pop up after you perform an action - like "Profile updated successfully" or "Invalid password". They improve user experience by giving immediate feedback.
Flask has a built-in flash() function. In your route, call flash() with a message and optional category:
from flask import flash, redirect, url_for
@app.route('/update_profile', methods=['POST'])
def update_profile():
# Process form data...
flash('Profile updated successfully!', 'success')
return redirect(url_for('profile'))
@app.route('/login', methods=['POST'])
def login():
# Check credentials...
if not valid:
flash('Invalid username or password', 'error')
return redirect(url_for('login'))
The second argument is the category. Common categories are 'success', 'error', 'info', and 'warning'. You can make your own categories too.
In your template, use get_flashed_messages() to retrieve and display them. Here's a simple way to show all flash messages:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
<button type="button" class="close" data-dismiss="alert">
<span>×</span>
</button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
If you're using Bootstrap (which you probably are), you can style them nicely. Bootstrap's alert classes work perfectly with flash categories:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<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 %}
{% endif %}
{% endwith %}
The alert-dismissible class and the close button make messages auto-dismissable. Users can click the X to close them, or they can disappear after a few seconds with JavaScript.
Flash messages are shown only once. Once you call get_flashed_messages(), they're cleared from the session. This prevents the same message from showing up on every page load.
Use flash messages for any important user feedback: successful operations, errors, warnings, or just informational messages. They keep your users informed about what's happening.
Try it Yourself ->