当我尝试在我在下面的AttributeError: 'BaseQuery' object has no attribute 'check_password
中创建的用户对象上调用check_password
时,我收到forms.py
'。以下是发生问题的两行:
user = User.query.filter_by(userID = self.userID.data)
if user and user.check_password(self.password.data):
...
相关的源代码如下。我知道check_password()
方法有效,因为我可以在models.py
内调用它。我不确定为什么我可以访问用户模型而不是check_password
函数。
forms.py
...
from .models import User
class LoginForm(Form):
...
def validate(self):
if not Form.validate(self):
return False
***user = User.query.filter_by(userID = self.userID.data)***
***if user and user.check_password(self.password.data)***:
return True
else:
self.userID.errors.append("Invalid user ID or password")
return False
models.py
from app import db
from flask.ext.login import LoginManager, UserMixin
from werkzeug import generate_password_hash, check_password_hash
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
social_id = db.Column(db.String(64), nullable=False) #could have duplicate
userID = db.Column(db.String(64), nullable=False)
email = db.Column(db.String(64), nullable=True)
pwdhash = db.Column(db.String(54), nullable=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __init__(self, social_id, userID, email, password):
if social_id:
self.social_id = social_id #not required if not using Facebook login
if userID:
self.userID = userID
self.email = email.lower()
if password:
self.set_password(password)
assert self.check_password(password)
def set_password(self, password):
self.pwdhash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
答案 0 :(得分:4)
User.query.filter_by()
将返回查询。如果您想要查询的第一个结果,则需要调用first()
,即
User.query.filter_by(...).first()