0
将FlaForce和SQLAlchemy与WTForms结合使用。从用户名和电子邮件字段获取数据并确保它不在数据库中。这是我现在要做的。将参数传递给成为函数关键字的类
class IsUnique(object):
def __init__(self, db_field=None):
self.db_field = db_field
def __call__(self, form, field):
data = field.data
if self.db_field=='name':
if User.query.filter_by(name=data).first() != None:
raise ValidationError('Sorry, that username is taken.')
if self.db_field=='email':
if User.query.filter_by(email=data).first() != None:
raise ValidationError(
'Sorry, that email address has already been registered.'
)
我想这样做是对db_field参数传递给类实例作为一个字符串,并将其传递到User.query.filter_by(db_field=data
。不幸的是,我所知道的是如何使用if语句,该语句有效,但有点麻烦。有一种方法可以做到这一点,但我不知道如何。