Flash Messages
Flash messages are one‑time notifications displayed to the user after an action – for example, "Login successful", "Item added", or "Error: invalid input". They are stored in the session and cleared after being displayed.
Flashing a Message
from flask import flash, redirect, url_for
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form['username'] == 'admin' and request.form['password'] == 'secret':
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid credentials.', 'danger')
return render_template('login.html')The second argument is the category (e.g., `success`, `danger`, `warning`, `info`).Displaying Flash Messages in Template
In your base template, add a loop to display all messages.
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}Why Use Flash Messages?
- They persist across redirects (unlike just passing variables).
- Automatically cleared after one request.
- Great for user feedback.
Requirements
Flash messages use the session so you must set a `SECRET_KEY`.
app.config['SECRET_KEY'] = 'your-secret-key-here'Two Minute Drill
"- Use `flash('message' 'category')` to store a message.
- Retrieve with `get_flashed_messages(with_categories=true)`.
- Messages disappear after being displayed.
- Requires `SECRET_KEY` to be set.
Need more clarification?
Drop us an email at career@quipoinfotech.com
