简体   繁体   English

NameError:在我的表单中未定义名称“用户名”

[英]NameError: name 'username' is not defined in my form

@app.route('/register/go', methods=['GET', 'POST'])
def register():
    global username, password, email
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']

    cursor.execute('SELECT * FROM accounts WHERE username = %s', [username])
    account = cursor.fetchone()
    if account:
        cursor.execute('INSERT INTO accounts VALUES(NULL,%s, %s, %s)', [username, password, email])
        connection.commit()
        msg = 'success'

    # Show registration form with message (if any)
    return render_template('register.html')

I keep on getting error as "NameError: name 'username' is not defined" for the below line of code 我持续收到以下代码行的错误,因为“ NameError:未定义名称'用户名'”

cursor.execute('SELECT * FROM accounts WHERE username = %s', [username])

You need to give username a value, even if you make it global. 即使您将username为全局,也需要为其赋予一个值。 Use this: 用这个:

username = ''
global username

The variable won't be set if the if condition fails. 如果if条件失败, if不会设置该变量。 But if the form isn't filled out, you shouldn't insert into the database at all. 但是,如果不填写表单,则根本不应该将其插入数据库。 You should move that code into the if block. 您应该将该代码移至if块中。

Also, your if account condition is backwards. 另外,您的if account条件是向后的。 You should only insert a row if the account doesn't already exist. 如果该帐户尚不存在,则只应插入一行。

@app.route('/register/go', methods=['GET', 'POST'])
def register():
    global username, password, email
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']

        cursor.execute('SELECT * FROM accounts WHERE username = %s', [username])
        account = cursor.fetchone()
        if account:
            msg = 'username already taken'
        else:
            cursor.execute('INSERT INTO accounts VALUES(NULL,%s, %s, %s)', [username, password, email])
            connection.commit()
            msg = 'success'
    else:
        msg = 'Username and password are required'

    # Show registration form with message (if any)
    return render_template('register.html')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM