1

I have implemented a simple Flask application with login and register routes and I want to flash messages when username passwords are not matched. This is a part of my index and login routes,

@app.route('/')
@login_required
def index():
    return 'Hello World'

@app.route("/login", methods=["GET", "POST"])
def login():

    # Forget any user_id
    session.clear()

    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            flash("Must provide username")
            return redirect("/login")

        #And so on...

    if request.method == "GET":
        render_template("login.html")

The problem is that the flash message does not appear when I submit the form with blank inputs. Even so, the register route which has the same code renders the flash message without any error,

@app.route("/register", methods=["GET", "POST"])
def register():

    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            flash("Must provide username")
            return redirect("/register")
      
        #And so on...

    if request.method == "GET":
            render_template("register.html")

I have included Jinja templating in my templates. Can someone please point out why it is not working in only the login route?

VC.One
  • 14,790
  • 4
  • 25
  • 57

1 Answers1

1

Your login function clears the session, even if request.method is GET:

session.clear()

Because flash messages are stored in the session, by the time the login form is rendered, the messages have already been removed.

Depending on what the rest of login looks like, you may want to clear the session only if request.method is POST.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62