Home > database >  How do I show an error message when I have an invalid log in?
How do I show an error message when I have an invalid log in?

Time:10-16

I'm working on a web app right now and I don't know how to display an error message when the user types in an invalid log in name. How do I go about this?

this is my login.html

{% block body %}
  <h1>Login</h1>
  {% if error %}
    <p>Invalid Username</p>
  {% endif %}
  
  <form method="POST" action="{{ url_for('login') }}">
    <input type="text" name="username" placeholder="Your Username">
    <input type="submit" value="Submit">
</form>

<a href='{{variable6}}'>Sign Up</a>
{% endblock %}

this is my app.py

@app.route("/login", methods=["GET", "POST"])
def login():
    if flask.request.method == "GET":
        return flask.render_template("login.html")
    if flask.request.method == "POST":
        username = flask.request.form["username"]
        cursor.execute(
            "SELECT user_name FROM public.users WHERE user_name = %s", [username]
        )
        results = cursor.fetchall()
        if len(results) != 0: # if a user exists, "log" them in
            return flask.redirect(flask.url_for("main"))
        else:
            return flask.render_template("login.html")

CodePudding user response:

I believe that your problem is that you are not defining what the "error" variable is, you could fix this by when you are returning the render_template in the last line of app.py, adding error=True, leaving you with this as your last line for app.py.

return flask.render_template("login.html", error=True)

As otherwise Jinja (the templating language you used in login.html) would not know what error and would get the type None as the value of error in the {% if error %} statement in login.html and since None is not equal to true, it would skip over the code you want to run.

Hope this helps :)

  • Related