0

Using WTForms with Flask and SQLAlchemy. Taking data from a username and email field and making sure it's not already in the database. Here's what I have to do right now.

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.'
                    )

What I would like to do is to pass the db_field argument to the class instance as a string and pass it into User.query.filter_by(db_field=data. Unfortunately all I know how to do is use an if statement, which works, but is kinda cumbersome. There's gotta be a way to do this right, but I don't know how.

rspears69
  • 435
  • 1
  • 7
  • 19

1 Answers1

2

You can pass keyword arguments as a dict, like this:

def __call__(self, form, field):
    key = self.db_field # 'name' or 'email'
    params = { key: field.data }
    if User.query.filter_by(**params).first() != None:
        raise ValidationError('Sorry, that {} is taken.'.format(key))
Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436