' NoneType'对象没有属性'用户名'?

时间:2016-11-05 21:35:55

标签: python flask sqlalchemy

所以我收到了这个错误

AttributeError:' NoneType'对象没有属性'用户名'

任何建议,

Models.py

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(20), unique=True)


    def __init__(self, username, password):
        self.username = username
        self.password= bcrypt.generate_password_hash(password, 10)




    def is_authenticated(self):
        return True


    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return (self.id)


    def __repr__(self):
        return '<User %r>' % self.username

Views.py

@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    user = User(request.form['username'] , request.form['password'] )
    username = request.form['username']
    password = request.form['password']
    storeduser = User.query.filter_by(username=username).first()
    if storeduser.username is not None and storeduser.username == request.form['username']:
        return 'User already Exist !'
    else:
        db.session.add(user)
        db.session.commit()
        flash('User successfully registered')
        return redirect(url_for('index'))

几乎如果客户端用户名与当前用户名输出匹配 现有用户注册,如果没有注册用户名。

我在我的模特中引用我的用户名(如果你想知道的话)

1 个答案:

答案 0 :(得分:1)

User.query.filter_by(username=username).first()查询返回None,表示找不到用户。

您需要首先测试storeduser是否不是None不是 storeduser.username

if storeduser is not None and storeduser.username == request.form['username']:
    return 'User already Exist !'

因为您在request.form['username']上查询后一项测试是多余的,所以您只需要使用;

if storeduser is not None:
    return 'User already Exist !'