Search code examples
pythonflaskweb-applicationsattributeerror

Creating register form with Flask - AttributeError: 'ValueError' object has no attribute 'name'


I've been trying to get my register page to work for a couple days now. I think I'm close , but now I'm receiving the following error message in my terminal when I try to click register from the login page:

File "/home/ubuntu/workspace/pset7/finance/application.py", line 175, in errorhandler

return apology(e.name, e.code)

AttributeError: 'ValueError' object has no attribute 'name'

Here is my code from the lines the error is pointing to (I didn't write them, they were provided with the distribution code):

def errorhandler(e):
"""Handle error"""
return apology(e.name, e.code)

Any help would be greatly appreciated. I will include my register function code just in case that helps:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Ensure password == confirmation
        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("password and confirmation do not match", 403)

        # Ensure username is not already taken
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))
        if len(rows) == 1:
            return apology("username already taken. please choose another", 403)

        # Add new user to the database
        session["user_id"] = db.execute("INSERT INTO users(username, hash) VALUES(:username, :hash)", username=request.form.get("username"), \
        hash=generate_password_hash(request.form.get("password")))

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

Thanks!


Solution

  • I just solved it! I noticed this: ERROR in app: Exception on /register [GET]

    So it seemed like the error must be related the the [GET] side of things. I took a look at the code's /login function and it had the following else statement at the bottom of its block:

    (I changed the login.html to register.html)

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("register.html")
    

    I guess the problem was that I was handling POST requests, but not GET requests. This last else statement ensures that the page will be rendered for someone following the link. Thanks again for the help!