How to set up flash message in html template in flask app

To set up a flash message in an HTML template in a Flask app, follow these steps:

  1. Import the flash module from the flask package in your Flask app:
from flask import flash
  1. Add a secret key to your Flask app configuration. The secret key is required for the flash messages to work properly. You can generate a secret key using a secure random generator. Here's an example of how to set the secret key:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
  1. In your Flask view function, use the flash function to add a message to the flash message queue:
@app.route('/example')
def example():
    flash('This is an example flash message', 'success')
    return render_template('example.html')

In the above example, 'This is an example flash message' is the message you want to display, and 'success' is the category of the message (e.g., success, error, warning, info).

  1. In your HTML template, add a block to display the flash messages:
{% with messages = get_flashed_messages() %}
    {% if messages %}
        <ul class="flash-messages">
            {% for message in messages %}
                <li class="{{ message[1] }}">{{ message[0] }}</li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}

The above code retrieves the flash messages using the get_flashed_messages() function and loops through each message to display it. The message[1] represents the category of the message, and message[0] represents the content of the message.

That's it! With these steps, you have set up flash messages in your HTML template in a Flask app.