Flash Messages in Flask
Key Concepts
- Flash Messages
- Setting Flash Messages
- Displaying Flash Messages
- Categories for Flash Messages
- Using Flash Messages in Templates
Flash Messages
Flash messages are temporary messages stored in the session that are displayed to the user once and then discarded. They are commonly used to provide feedback after form submissions, redirects, or other user interactions.
Setting Flash Messages
To set a flash message, you use the flash()
function from the Flask library. This function takes two arguments: the message to be displayed and an optional category (e.g., 'success', 'error', 'info').
from flask import Flask, flash, redirect, url_for app = Flask(__name__) app.secret_key = 'secret' @app.route('/submit', methods=['POST']) def submit(): flash('Form submitted successfully!', 'success') return redirect(url_for('home'))
Displaying Flash Messages
To display flash messages in your templates, you use the get_flashed_messages()
function. This function retrieves all the flash messages stored in the session and removes them afterward.
<ul> {% for message in get_flashed_messages() %} <li>{{ message }}</li> {% endfor %} </ul>
Categories for Flash Messages
Flash messages can be categorized to allow for different styling or handling based on the type of message. Categories are specified when setting the flash message and can be retrieved when displaying them.
from flask import Flask, flash, redirect, url_for app = Flask(__name__) app.secret_key = 'secret' @app.route('/submit', methods=['POST']) def submit(): flash('Form submitted successfully!', 'success') flash('There was an error processing your request.', 'error') return redirect(url_for('home'))
<ul> {% for category, message in get_flashed_messages(with_categories=true) %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul>
Using Flash Messages in Templates
Flash messages are typically displayed at the top of the page or in a designated area. You can use CSS to style the messages based on their categories, making it easier for users to understand the feedback.
<style> .success { color: green; } .error { color: red; } </style> <ul> {% for category, message in get_flashed_messages(with_categories=true) %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul>