Skip to content

Login View

A login view typically:

  1. shows a login form (GET)
  2. validates credentials (POST)
  3. calls login_user(user)login_user(user)
  4. redirects to a protected page

Example (simplified)

from flask import render_template, redirect, url_for, request, flash
from flask_login import login_user
from werkzeug.security import check_password_hash
 
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form.get("username", "")
        password = request.form.get("password", "")
 
        user = User.query.filter_by(username=username).first()
        if not user or not check_password_hash(user.password_hash, password):
            flash("Invalid username or password", "error")
            return redirect(url_for("login"))
 
        login_user(user)
        return redirect(url_for("dashboard"))
 
    return render_template("login.html")
from flask import render_template, redirect, url_for, request, flash
from flask_login import login_user
from werkzeug.security import check_password_hash
 
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form.get("username", "")
        password = request.form.get("password", "")
 
        user = User.query.filter_by(username=username).first()
        if not user or not check_password_hash(user.password_hash, password):
            flash("Invalid username or password", "error")
            return redirect(url_for("login"))
 
        login_user(user)
        return redirect(url_for("dashboard"))
 
    return render_template("login.html")

Remember to use PRG

After POST, redirect to avoid double submissions.

Next improvements

In real apps, you’ll typically:

  • use Flask-WTF for login form
  • rate-limit login attempts
  • add β€œnext” parameter support for redirects

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did