y'all. My register function seems to work just fine when inputting new and different usernames. However, when I tested it for the 403 error (ie the one which checks if there is an already existing username as the one inputted by the user), I get this error when I intentionally put the same username.

RuntimeError: UNIQUE constraint failed: users.username

Here is the code for the function

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""
    if request.method == "GET":
        return render_template("register.html")
    elif request.method == "POST":
                # Ensure username was submitted
        if not request.form.get("user"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)
        # If passwords do no match
        elif request.form.get("password") != request.form.get("passwordconf"):
            return apology("must provide matching password", 403)

        rows = db.execute("SELECT * FROM users WHERE username = :username",
        if rows == 1:
            return apology("a user has already taken that name", 403)
            hash = generate_password_hash(request.form.get("password"))
            new_user_id = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)",
                                 username=request.form.get("user"), hash=hash)

            # Redirect user to home page
            return redirect("/")

1 Answer 1


A problem is here: if rows == 1:. Remember, execute returns a list of dictionaries, therefore that conditional is never true.

  • Welp forgot to put len(rows) == 1 instead. Thank you so much.
    – Sorphil
    Apr 22, 2020 at 1:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .