If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

from validators import translate, Validator

class IS_NOT_IN_DB_ANYCASE(Validator):
    """
    example::

        INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table))

    makes the field unique
    """

    def __init__(
        self,
        dbset,
        field,
        error_message='value already in database or empty',
        allowed_override=[],
        ignore_common_filters=False,
    ):

        from dal import Table
        if isinstance(field, Table):
            field = field._id

        if hasattr(dbset, 'define_table'):
            self.dbset = dbset()
        else:
            self.dbset = dbset
        self.field = field
        self.error_message = error_message
        self.record_id = 0
        self.allowed_override = allowed_override
        self.ignore_common_filters = ignore_common_filters

    def set_self_id(self, id):
        self.record_id = id

    def __call__(self, value):
        if isinstance(value,unicode):
            value = value.encode('utf8')
        else:
            value = str(value)
        if not value.strip():
            #return (value, translate(self.error_message))
            return (value, self.error_message)
        if value in self.allowed_override:
            return (value, None)
        (tablename, fieldname) = str(self.field).split('.')
        table = self.dbset.db[tablename]
        field = table[fieldname]
        #subset = self.dbset(field == value, ignore_common_filters=self.ignore_common_filters)
        subset = self.dbset(field.like(value), ignore_common_filters=self.ignore_common_filters)
        id = self.record_id
        if isinstance(id, dict):
            fields = [table[f] for f in id]
            row = subset.select(*fields, **dict(limitby=(0, 1), orderby_on_limitby=False)).first()
            if row and any(str(row[f]) != str(id[f]) for f in id):
                #return (value, translate(self.error_message))
                return (value, self.error_message)
        else:
            row = subset.select(table._id, field, limitby=(0, 1), orderby_on_limitby=False).first()
            if row and str(row.id) != str(id):
                #return (value, translate(self.error_message))
                return (value, self.error_message)
        return (value, None)

 

Comments (0)


Hosting graciously provided by:
Python Anywhere