Flashing messages in Flask App

From TRCCompSci - AQA Computer Science
Revision as of 12:39, 29 October 2019 by Admin (talk | contribs) (Created page with "=Import flash= At the top of your 'views.py' add 'flash' to the 'Flask' import line, mine now looks like this: <syntaxhighlight lang=python> from flask import Flask, Response...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Import flash

At the top of your 'views.py' add 'flash' to the 'Flask' import line, mine now looks like this:

from flask import Flask, Response, flash, redirect, url_for, request, session, abort

Edit main template

Now open your main HTML template, mine is called 'Layout.html'. It will currently include a 'div' tag with a class set to 'body-content', you can also find this tag by looking for the content block so look for '{% block content %}{% endblock %}'. Before this div add the following:

    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <div class="alert alert-info alert-dismissible">
                {% for message in messages %}
                    <strong>Error!</strong> {{message}}
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                {% endfor %}
            </div>
        {% endif %}
    {% endwith %}

This will get the messages created using 'flash' in the code, if messages are present it will create a 'div' for each message and set the class to be an 'alert'. The 'alert' will include a button to dismiss the 'alert'.

Adding the flash messages