Flashing messages in Flask App

From TRCCompSci - AQA Computer Science
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

Now you can go through your routes and add any messages required. For example this is my 'login' route:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            userpass = form.password.data
            username = form.username.data
            db = Database()
            sql ="select * from users where UserID='%s' and UserPass='%s'" % (username,userpass)
            rows=db.select(sql)
            if len(rows)==0:
                flash("Username & Password combination not found.")
                return render_template('login.html', title='Sign In', form=form)
            else:
                user = User(username)
                login_user(user)
                return redirect('/')
        else:
            flash("Data entered is not valid.")
    return render_template('login.html', title='Sign In', form=form)

The below example is my 'signup' route:

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignUpForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            confirm = form.confirm.data
            email = form.email.data
            dob = form.DOB.data
            mf = form.MF.data
            if password == confirm:
                db = Database()
                sql ="select * from users where UserID='%s'" % (username)
                rows=db.select(sql)
                if(len(rows)==0):
                    db=Database()
                    sql = "insert into users values('%s','%s','%s','%s','%s')" % (username,password,email,dob,mf)                      
                    if db.execute(sql):
                        return redirect('/')
                    else:
                        flash("User insert failed.")
                else:
                    flash("The username already exists.")
            else:
                flash("You password and confirm must be the same.")
        else:
            flash("Data entered is not valid.")
    return render_template('signup.html', title='Sign Up', form=form)