How To Make A Login Page Flask

A login page is an essential component of many web applications. It allows users to securely access their personal accounts and ensures that the application’s resources are protected. In this article, I will guide you through the process of creating a login page using Flask, a popular web framework for Python. I will share my personal insights and provide in-depth explanations to help you understand the concepts and techniques involved.

Setting up the Flask Environment

Before we dive into building the login page, let’s make sure we have Flask properly installed and set up.

  1. Create a new directory for your project and navigate to it in your terminal.
  2. Set up a virtual environment by running the command python -m venv venv.
  3. Activate the virtual environment by running source venv/bin/activate on macOS/Linux or venv\Scripts\activate on Windows.
  4. Install Flask by running pip install flask.
  5. Create a new Python file named app.py in the project directory.

Creating the Login Page

Now that our Flask environment is set up, let’s start building the login page. Open the app.py file and import the necessary modules:

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

We’re using Flask’s render_template function to render our HTML templates, request module to handle incoming requests, and redirect to redirect the user after successful login. We’ll also be using the SQLAlchemy module to interact with our database.

Next, let’s create our Flask application instance and configure the database:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

The SQLALCHEMY_DATABASE_URI configuration tells Flask where to find our SQLite database file. You can replace this with other database systems like PostgreSQL or MySQL.

Now, let’s define our User model to represent the users in our database:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)

The User model has three fields: id, username, and password. The username field is unique, meaning each user must have a unique username. The password field stores the encrypted password for each user.

Next, let’s create a route for our login page:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        
        if user and password == user.password:
            return redirect('/dashboard')
        else:
            return render_template('login.html', error='Invalid username or password')
    else:
        return render_template('login.html')

In this route, we first check if the request method is POST, which means the user has submitted the login form. We then retrieve the username and password from the form and query the database to find a user with the given username. If the user exists and the password matches, we redirect them to the dashboard page. Otherwise, we render the login template again with an error message.

Building the Login Template

To make our login page visually appealing, we’ll create an HTML template. Create a new folder named templates in your project directory, and inside it, create a file named login.html.

In the login.html file, we’ll add the following HTML code:

<h2>Login</h2>

{% if error %}
  <p class="error">{{ error }}</p>
{% endif %}

<form action="/login" method="POST">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required>

  <input type="submit" value="Login">
</form>

The template consists of a login form that collects the username and password from the user. If there’s an error message, we display it above the form. The form’s action is set to /login, which is the URL we defined for the login route in our Flask application.

Conclusion

Creating a login page in Flask involves setting up the environment, defining the necessary routes and models, and creating an HTML template for the login form. We’ve covered the fundamental steps and provided a basic implementation to get you started. Remember to handle user authentication securely, store passwords in hashed form, and consider adding additional features like password reset and account verification to enhance the login experience. Happy coding!