In this Flask Tutorial we are going to learn about Flash Messages in Flask, good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it next request and only next request. This is usually combined with a layout template that does this. Note that browsers and sometimes web servers enforce a limit on cookie sizes. This means that flashing message that are too large for session cookies causes message flashing to fail silently.
OK we are going to use our Flask Project from the previous lesson, where we have a login form, so now i want when a user enter wrong password or username, i want to show error in Flask Flash Messages.
This is our form.py file.
1 2 3 4 5 6 7 8 9 |
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import InputRequired class LoginForm(FlaskForm): username = StringField('Username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) |
And this is our app.py file with our required view functions and you can see that we have also added our login view function in here. so in the Login view function we need to write our Flask Flash Messages, till now we haven’t learned about database functionality in Flask, we are going to just manually check the username and password. make sure that you have imported the flash message.
1 2 3 4 |
if form.validate_on_submit(): if request.form['username'] != 'geekscoders' \ or request.form['password'] != '12345': flash("Invalid Credentials, Please Try Again") |
This is the complete code for app.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
from flask import Flask, render_template, redirect,\ url_for, request, flash from form import LoginForm #create the object of Flask app = Flask(__name__) app.config['SECRET_KEY'] = 'hardsecretkey' #creating our routes @app.route('/') def Index(): name = 'Geekscoders.com' return render_template('index.html', data = name) @app.route('/login', methods = ['GET', 'POST']) def Login(): form = LoginForm() if form.validate_on_submit(): if request.form['username'] != 'geekscoders' \ or request.form['password'] != '12345': flash("Invalid Credentials, Please Try Again") else: return redirect(url_for('Index')) return render_template('login.html', form=form) @app.route('/contact') def Contact(): return render_template('contact.html') @app.route('/about') def About(): return render_template('about.html') @app.errorhandler(404) def page_not_found(e): return render_template('404.html') @app.errorhandler(500) def internal_server_error(e): return render_template('500.html') #run flask app if __name__ == "__main__": app.run(debug=True) |
We are going to show our Flask Flash Messages in login.html, so you can use this code for showing the Flash Messages, also we have added a simple bootstrap design for our flash message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
{% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} <div class="alert alert-success alert-dismissable" role="alert"> {{message}} </div> {% endfor %} {% endif %} {% endwith %} |
This is our complete code for login.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
{% extends 'base.html' %} {% block title %}Login{% endblock %} {% block body %} <div class="container"> <h1>Login here</h1> <br> <br> <hr> {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} <div class="alert alert-success alert-dismissable" role="alert"> {{message}} </div> {% endfor %} {% endif %} {% endwith %} <form action="" method="post" novalidate> {{form.csrf_token}} <p> {{form.username.label}} {{form.username(size=32)}} {% for error in form.username.errors %} <span style="color:red;"> {{error}} </span> {% endfor %} </p> <p> {{form.password.label}} {{form.password(size=32)}} {% for error in form.password.errors %} <span style="color:red;"> {{error}} </span> {% endfor %} </p> <p> <input type="submit" value="Login" class="btn btn-success"> </p> </form> </div> {% endblock %} |
These are the rest of the files for the project.
templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" > <!-- Add Icon --> <link rel="icon" href="{{url_for('static', filename = 'py.png')}}"/> </head> <body> <nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{{url_for('Index')}}">GeeksCoders</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{{url_for('Index')}}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_for('Contact')}}">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_for('About')}}">About</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <a href="{{url_for('Login')}}"> <button class="btn btn-success navbar-btn">Login</button> </a> </nav> {% block body %} {% endblock %} <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" > </script> </body> </html> |
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block body %} <div class="container"> <h1>Welcome to our home page</h1> <h3>Welcome to . {{data}}</h3> </div> {% endblock %} |
templates/contact.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{% extends 'base.html' %} {% block title %}Contact{% endblock %} {% block body %} <div class="container"> <h1>This is contact page</h1> </div> {% endblock %} |
templates/about.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{% extends 'base.html' %} {% block title %}About{% endblock %} {% block body %} <div class="container"> <h1>This is our about page</h1> </div> {% endblock %} |
templates/500.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{% extends 'base.html' %} {% block title %}Server Error {% endblock %} {% block body %} <div class="container"> <h1>Internal Server Error </h1> </div> {% endblock %} |
templates/404.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{% extends 'base.html' %} {% block title %}Page Not Found {% endblock %} {% block body %} <div class="container"> <h1>Page Not Found</h1> </div> {% endblock %} |
Run your flask project give wrong username and password you will see the error.
