-1
當我嘗試在我在下面的forms.py
中創建的用戶對象上調用check_password
時,我收到AttributeError: 'BaseQuery' object has no attribute 'check_password
。下面是發生問題的兩條線:在Flask中查詢數據庫
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)