Skip to content

Flash Messages

Flash messages are one-time messages stored in the user’s session.

They’re commonly used after:

  • successful form submission
  • login/logout
  • errors like “invalid password”

Flashing a message

from flask import flash, redirect, url_for
 
@app.route("/subscribe", methods=["POST"])
def subscribe():
    # ...do work...
    flash("Subscribed successfully!", "success")
    return redirect(url_for("home"))
from flask import flash, redirect, url_for
 
@app.route("/subscribe", methods=["POST"])
def subscribe():
    # ...do work...
    flash("Subscribed successfully!", "success")
    return redirect(url_for("home"))

The second argument ("success""success") is a category.

Display flash messages in templates

In your base template:

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul>
      {% for category, message in messages %}
        <li class="flash {{ category }}">{{ message }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul>
      {% for category, message in messages %}
        <li class="flash {{ category }}">{{ message }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

Requirements

Flashing uses sessions, so you need SECRET_KEYSECRET_KEY configured.

Best practice

Use flash + redirect (PRG pattern) so the message shows on the GET page.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did