Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Flask Jinja2 Template Project to Implement HTML5 Form Validation & Show Custom Error Messages in Browser

Posted on March 18, 2023

 

First, we need to create our Flask app and import the necessary modules:

pip install flask
app.py
Python
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)

 

Next, we need to define our form and its validation rules. In this example, we’ll create a simple login form with two fields: “username” and “password”. We’ll require both fields to be filled out, and we’ll display a custom error message if either field is left blank:
Python
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.

Recent Posts

  • Python 3 Flask Jinja2 Template Project to Implement HTML5 Form Validation & Show Custom Error Messages in Browser
  • Node.js Tutorial to Rename All Files in Directory With Custom Pattern Using fs Module
  • FFMPEG Command to Create MP4 Video Slideshow From Multiple Images in Command Line
  • How to Add Let’s Encrypt SSL Certificate to Domain Using Certbot in Nginx
  • Node.js Fluent-FFMPEG Audio Pitch & Speed Changer With Live Preview in Browser Using Express
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme