How to Create a Login Page in Python?

Estimated read time 2 min read

To create a login page in Python, you’ll need to use a web framework like Flask or Django. Here’s a basic example using Flask:

  1. Install Flask: If you haven’t already, install Flask by running pip install flask in your terminal.
  2. Import Flask and set up the app: Import the Flask library and create an instance of the app.
from flask import Flask

app = Flask(__name__)
  1. Define the login route and HTML form: Use the @app.route() decorator to define a route for the login page, and create an HTML form that prompts the user for their username and password.
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Handle form submission
        username = request.form['username']
        password = request.form['password']
        # Check if username and password are valid
        if username == 'myusername' and password == 'mypassword':
            # Redirect to homepage if login is successful
            return redirect('/')
            # Show error message if login fails
            return render_template('login.html', error='Invalid username or password')
        # Show login form if method is GET
        return render_template('login.html')
  1. Define the HTML templates: Create a folder called templates in your project directory, and create a file called login.html in this folder. This file should contain the HTML code for the login form.
{% extends 'base.html' %}

{% block content %}
{% if error %}
    <p class="error">{{ error }}</p>
{% endif %}
<form method="post">
    <input type="text" name="username"><br>
    <input type="password" name="password"><br>
    <input type="submit" value="Login">
{% endblock %}
  1. Run the app: Use the method to start the Flask development server.
if __name__ == '__main__':

This is a very basic example, and you’ll likely want to add more features (such as database integration, password hashing, etc.) to make the login page more secure and functional. But this should give you a starting point for creating a simple login page in Python with Flask.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply