Question

I'm trying to make a unique validator for WTForms that works with Google App engine. I have a model called Question and a field called 'slug' that I need to be unique. I found this really nice example on Stackoverflow, but it uses SQLAlchemy. I wanted to see if someone could help me figure out how to get it to work with Google App Engine instead of SQLAlchemy.

The SQLAlchemy example: Unique validator in WTForms with SQLAlchemy models

class Unique(object):
    """ validator that checks field uniqueness """
    def __init__(self, model, field, message=None):
        self.model = model
        self.field = field
        if not message:
            message = u'this element already exists'
        self.message = message

    def __call__(self, form, field):         
        check = self.model.query.filter(self.field == field.data).first()
        if check:
            raise ValidationError(self.message)

I think the "check" line needs to be changed to work with GAE? But I'm not the best with passing stuff like that to objects.

I know the GAE query would be something like... Question.query(Question.slug = slug)

Was it helpful?

Solution

I was able to do it with this...

class UniqueValidator(object):
""" validator that checks field uniqueness """
def __init__(self, model, field, message=None):
    self.model = model
    self.field = field
    if not message:
        message = u'Existing element with the same value.'
    self.message = message

def __call__(self, form, field):
    existing = self.model.query(getattr(self.model,self.field) == field.data).get()
    if 'id' in form:
        id = int(form.id.data)
    else:
        id = None
    if existing and (id is None or id != existing.key.id()):
        raise ValidationError(self.message)

and

class QuestionEditForm(Form):
id = HiddenField('id')
question = TextField('Question', [validators.Required(),
                                  validators.Length(min=4, max=225)])
slug = TextField('Slug', validators = [validators.Required(),
                                       validators.length(max=200),
                                       UniqueValidator(
                                           Question,
                                           'slug',
                                           'Existing slug with the same value.'
                                       )])`enter code here`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top