local variable 'message' referenced before assignment

having trouble rendering 'user_message' variable in my html page from my python editor, the error page states "local variable 'message' referenced before assignment". I've looked at previous questions / answers on here but can't figure this out. Below is my code. Grateful for some help. Thank you

if request.method == "POST":
        new_user = request.form["username"]
        registered_users = users()
        if new_user in registered_users:
            user_message = "Sorry, this username is taken, please choose another"
        else:
            if request.method == "POST":
                user_list = open("data/users.txt", "a")
                user_list.write(new_user + "\n")
                session['user'] = new_user
                flash("Thanks for registering {}!".format(request.form["username"]))
    return render_template("register.html", register_message = user_message)

1 answer

  • answered 2018-11-08 12:15 Vineeth Sai

    You are using the user_message variable in your return statement but only defined it in one case, i.e the if statement. So you must define it in else block too, Or you can define user_message above the if-else block and override it in case user already existed. Look for the comment so as to where to fix.

    if request.method == "POST":
            new_user = request.form["username"]
            registered_users = users()
            if new_user in registered_users:
                user_message = "Sorry, this username is taken, please choose another"
            else:
                if request.method == "POST":
                    user_message = "This user name available !!!" # <--- You need to define it in the else branch too
                    user_list = open("data/users.txt", "a")
                    user_list.write(new_user + "\n")
                    session['user'] = new_user
                    flash("Thanks for registering {}!".format(request.form["username"]))
        return render_template("register.html", register_message = user_message)