I was implementing register in pset7 and I keep getting an error KeyError: 'id'. I checked the database and found that the user has been added to the database however the error mentioned keeps showing up. Here is my code for the register function

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

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

# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":

    #Make sure fields are not blank
    if not (request.form.get("username") or request.form.get("pass") or request.form.get("pass2")):
        return apology("Missing information !")
    elif request.form.get("pass") != request.form .get("pass2"):
        return apology("Passwords do not match !")
        hashPassword = pwd_context.encrypt(request.form.get("username"))

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

        if not result:
            return apology("Username taken !")

        row=db.execute("SELECT username from users where username=:user",user=request.form.get("username"))
        # remember which user has logged in
        session["user_id"] = row[0]["id"]

        # redirect user to home page
        return redirect(url_for("index"))

    return render_template("login.html")

1 Answer 1


True. row has no element id because row only contains the columns selected. But do you really need to do another SELECT? From the spec Hints:

If str is an INSERT, and the table into which data was inserted contains an autoincrementing PRIMARY KEY, then execute returns the value of the newly inserted row’s primary key.

If users.id is not autoincrement then you do need to correct the select.

You must log in to answer this question.

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