Flask redirect with error/success message

from flask import Flask, render_template, flash, url_for, request, redirect

app = Flask(__name__)
app.secret_key = b'a secret key'

@app.route('/buy', methods=['GET', 'POST'])
def buy():
    if request.method == 'POST':
        quantity = int(request.form['product_quantity'])
        if quantity > 5:
            flash('Out of stock! We have only 5 products in stock.', 'error')
            flash(f'Bought {quantity} items successfully!', 'success')
        return redirect(url_for('buy'))
    return render_template('buy.html')

    Flask Flash Demo

Checkout form

Below is an example form to show filtered flash messages using Flask. This example include two categories: success and error . Change the quantity from the dropdown in form submit to check the flash messages. The message box can be closed using the cross icon on upper right corner.

{% with errors = get_flashed_messages(category_filter=["error"]) %} {% if errors %} {% endif %} {% endwith %} {% with messages = get_flashed_messages(category_filter=["success"]) %} {% if messages %} {% endif %} {% endwith %}