How to build a simple login form using flask and python

In this tutorial we create a basic login form using Flask and Python. The form takes a username and password, checks the input against a hardcoded value, and displays a success or failure message based on whether the login is correct. This is a great starting point for understanding how authentication works in web apps.

It starts with designing a simple HTML form where the user can enter a username and password. When the form is submitted, the data is sent to the Flask server. In the Flask app, we use the ”request.form”  object to extract the entered values.

To keep things simple, we hardcode a correct username and password into the Python file. When a user submits the form, the app compares the input with the correct values. If both match, the user is successfully logged in and sees a welcome message. If the input is incorrect, the app displays an error message saying that the username or password is wrong.

Building a simple login form

Python Code

from flask import Flask, render_template, request

app = Flask(__name__)

# Hardcoded login credentials
VALID_USERNAME = "basha"
VALID_PASSWORD = "12345"

@app.route('/', methods=['GET', 'POST'])
def login():
    message = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username == VALID_USERNAME and password == VALID_PASSWORD:
            message = f"Welcome, {username}!"
        else:
            message = "Invalid username or password."

    return render_template('login.html', message=message)

if __name__ == '__main__':
    app.run(debug=True)

HTML Form

<!DOCTYPE html>
<html>
<head>
    <title>Simple Login</title>
</head>
<body>
    <h2>Login Form</h2>
    <form method="POST">
        <label>Username:</label>
        <input type="text" name="username"><br><br>

        <label>Password:</label>
        <input type="password" name="password"><br><br>

        <button type="submit">Login</button>
    </form>

    {% if message %}
        <p style="margin-top:20px; font-weight:bold;">{{ message }}</p>
    {% endif %}
</body>
</html>

We also use Jinja2 templating in the HTML file to display messages dynamically based on the result of the login attempt. This shows how Flask can pass data between the backend and frontend easily.

Output example :

Example 1 : Correct login

  Input:

  • Username: basha
  • Password: 12345

  Output:

             Welcome, basha! You have successfully logged in.

Example 2 : Incorrect password

Input:

  • Username: basha

  • Password: abc123

Output:

          Invalid username or password.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top