简体   繁体   中英

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

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

You need to give username a value, even if you make it global. Use this:

username = ''
global username

The variable won't be set if the if condition fails. 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.

Also, your if account condition is backwards. 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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