def register():
    """Register user."""

    if request.method == "POST":

        if not request.form.get("username"):
            return apology("must provide username")

        elif not request.form.get("password"):
            return apology("must provide password")

        elif not request.form.get("password_confirm"):
            return apology("must provide confirmation for password")

        elif request.form.get("password") != request.form.get("password_confirm"):
            return apology("password and confirmation don't match!")

        hash = pwd_context.encrypt("password")
        result = db.execute("INSERT INTO users(username, hash) VALUES(:username, :hash)",
                 username = request.form.get("username"), hash = hash)

        if not result:
            apology("Username already exists! Please try another one")

        rows = db.execute("SELECT * from users WHERE username = :username", username = request.form.get("username"))
        session["user_id"] = rows[0]["id"]

        return redirect(url_for("index"))

        return render_template("register.html")

This is my implementation for register function in pset7 finance website based on the Flask framework. When I try to register a second time using same username it allows me to do instead of replying with an apology. How do I fix this? Any help would be appreciated.

1 Answer 1


After comment: Missing return here apology("Username already exists! Please try another one")

Before comment: Add a unique index on username (in the database), then the insert will (should?) return a falsey value.

  • But when I use the schema command in sqlite3 it shows that this unique index command has been implemented
    – user34304
    Apr 14, 2017 at 11:25
  • Aha! answer edited. Apr 14, 2017 at 12:06

You must log in to answer this question.

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