Skip to content

Flask - Message Flashing

Good user interfaces provide feedback. After a user performs an action (like submitting a form, logging in, or deleting an item), it’s helpful to display a short, temporary message confirming the action or indicating success/failure. This is often called “message flashing”.

Flask’s flashing system provides a convenient way to record a message at the end of one request and access it in the next request (and only the next request). This is ideal for displaying status messages after redirects.

  1. Flashing: In a view function, call flash('Your message', 'category'). This stores the message (and optional category) in the user’s session.
  2. Redirecting (Optional but Common): Often, after flashing a message, you’ll redirect the user to another page using redirect(url_for(...)).
  3. Retrieving: In the view function or template for the next request, call get_flashed_messages() to retrieve the stored messages.
  4. Displaying: Render the retrieved messages in your template. Once retrieved, messages are removed from the session.
  5. Requires Secret Key: Since flashing uses the session, app.secret_key must be configured.
from flask import flash
# Flash a simple message
flash('Login successful!')
# Flash a message with a category for styling
flash('Invalid password.', 'error')
flash('Settings saved.', 'success')

Parameters:

  • message: The string containing the message to display.
  • category (optional): A string used to classify the message (e.g., ‘success’, ‘error’, ‘info’, ‘warning’). This is useful for applying different CSS styles.

This function is typically called within a template (often a base layout template) to retrieve and display messages.

{# Example in Jinja2 template #}
{# Method 1: Get messages without categories #}
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="alert-messages">
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endwith %}
{# Method 2: Get messages with categories for styling #}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class="alert-messages">
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}

Parameters:

  • with_categories=False (default): Returns a list of message strings.
  • with_categories=True: Returns a list of (category, message) tuples.
  • category_filter=[]: An iterable of categories to filter for. Only messages matching these categories will be returned (requires with_categories=True).

Example: Login Feedback with Flashing

This example shows a login form that flashes success or error messages.

  1. Create templates/layout_flash.html (Base Template):
<!doctype html>
<html>
<head>
<title>Flask Flashing Example</title>
<style>
.alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; }
.alert-success { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; }
.alert-error { color: #a94442; background-color: #f2dede; border-color: #ebccd1; }
.alert-messages { list-style: none; padding: 0; }
</style>
</head>
<body>
<h1>Flask Flashing Example</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class="alert-messages">
{% for category, message in messages %}
<li class="alert alert-{{ category|default('info') }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
</body>
</html>
  1. Create templates/index_flash_example.html (Home Page):
{% extends 'layout_flash.html' %}
{% block body %}
<p>Welcome! Please <a href="{{ url_for('login_page') }}">log in</a>.</p>
{% endblock %}
  1. Create templates/login_flash_example.html (Login Page):
{% extends 'layout_flash.html' %}
{% block body %}
<h2>Login</h2>
<form action="{{ url_for('do_login') }}" method=post>
<dl>
<dt>Username:</dt>
<dd><input type=text name=username></dd>
<dt>Password:</dt>
<dd><input type=password name=password></dd>
</dl>
<p><input type=submit value=Login></p>
</form>
{% endblock %}
  1. Create the Flask Application (app.py):
from flask import Flask, flash, redirect, render_template, request, url_for
import os
app = Flask(__name__)
# IMPORTANT: Use a secure, random secret key, ideally from env vars
app.secret_key = os.environ.get('SECRET_KEY', b'_5#y2L"F4Q8z\n\xec]/')
@app.route('/flash-example/')
def index():
return render_template('index_flash_example.html')
@app.route('/flash-example/login')
def login_page():
return render_template('login_flash_example.html')
@app.route('/flash-example/do-login', methods=['POST'])
def do_login():
# Simulate checking credentials
if request.form['username'] == 'admin' and request.form['password'] == 'secret':
flash('You were successfully logged in!', 'success')
# Redirect to index after successful login
return redirect(url_for('index'))
else:
flash('Invalid username or password. Please try again!', 'error')
# Redirect back to login page to show error
return redirect(url_for('login_page'))
if __name__ == "__main__":
app.run(debug=True, port=5007) # Use a different port if needed

Run the app, navigate to /flash-example/. Click the login link. Try logging in with incorrect credentials (error message shown on login page). Try logging in with correct credentials (admin/secret) (success message shown on index page).

Message flashing provides simple, effective feedback for users interacting with your web application.