赋值之前引用的局部变量“消息”

时间:2018-11-08 07:13:27

标签: html python-3.x

在通过python编辑器在html页面中呈现“ user_message”变量时遇到了麻烦,错误页面指出“分配前引用了本地变量'message'”。我在这里看过以前的问题/答案,但无法弄清楚。下面是我的代码。感谢您的帮助。谢谢

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 个答案:

答案 0 :(得分:0)

您在user_message语句中使用return变量,但仅在一种情况下定义了变量,即if语句。因此,您也必须在else块中定义它,或者可以在user_message块上方定义if-else并在用户已经存在的情况下覆盖它。寻找评论,以找出要修复的地方。

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)