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

时间:2019-09-13 06:51:22

标签: python pycharm nameerror

@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')

在下面的代码行中,由于“ NameError:未定义名称'username'”,我不断收到错误消息

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

2 个答案:

答案 0 :(得分:1)

即使将其设置为全局值,也需要给username赋予一个值。使用这个:

username = ''
global username

答案 1 :(得分:1)

如果if条件失败,则不会设置该变量。但是,如果不填写表单,则根本不应该将其插入数据库。您应该将该代码移到if块中。

此外,您的if account条件倒退了。如果该帐户尚不存在,则只应插入一行。

@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')