First, we need to create our Flask app and import the necessary modules:
pip install flask
app.py
1 2 3 4 5 6 |
from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) if __name__ == "__main__": app.run(debug=True) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@app.route('/', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] errors = [] if not username: errors.append("Please enter your username.") if not password: errors.append("Please enter your password.") if errors: return render_template('login.html', errors=errors) else: # Do login stuff here success_msg = "Login successful!" return render_template('login.html', success_msg=success_msg) else: return render_template('login.html') |
Note that if any errors are detected, we pass them to our HTML template using the errors
variable. We’ll use this variable to display our custom error messages.
Here, we’re setting the success_msg
variable to “Login successful!” when there are no errors, and passing it to the HTML template using the success_msg
variable.
Now, we just need to update our HTML template to display the success message when it’s present:
Now we need to create our HTML template. Here’s an example of how we can display our custom error messages:. For that we need to create the templates
folder and inside it we will be using the jinja2
template to render the error
messages as shown below
templates/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 |
<!doctype html> <html> <head> <title>Login</title> </head> <body> {% if errors %} <div class="alert alert-danger"> <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> {% endif %} {% if success_msg %} <div class="alert alert-success"> <p>{{ success_msg }}</p> </div> {% endif %} <form method="post"> <div> <label for="username">Username:</label> <input type="text" name="username" id="username"> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password"> </div> <div> <input type="submit" value="Login"> </div> </form> </body> </html> |
Note that we’re using Jinja2 template syntax to iterate over our errors
variable and display each error message as a list item.
That’s it! With this example, you should be able to create a simple form with custom error messages using Flask in Python 3.
Here, we’ve added an if
statement to check if the success_msg
variable is present, and display a success message with the contents of the success_msg
variable if it is.
That’s it! Now, when a user logs in successfully, they’ll see a success message displayed on the login page itself.
