def validate(self, obj, data, value, ctx=None): if ctx is None: ctx = {} errors = [] if isinstance(value, str): try: value = deserialize(value) except json.JSONDecodeError: raise exceptions.ValidationError( _('Does not appear to be valid json.')) if self.many and not isinstance(value, (list, tuple)): raise exceptions.ValidationError(_('Value must be a list.')) if not self.many: try: self.serializer.validate(obj=obj, data=value, ctx=ctx) except exceptions.ValidationError as exception: errors.append(exception.description) else: for item in value: try: self.serializer.validate(obj=obj, data=item, ctx=ctx) except exceptions.ValidationError as exception: errors.append(exception.description) if errors: raise exceptions.ValidationError(errors)
def validate_structure(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if isinstance(value, str): try: value = deserialize(value) except json.JSONDecodeError: raise exceptions.ValidationError( _('Does not appear to be valid json.')) if self.many and not isinstance(value, (list, tuple)): raise exceptions.ValidationError(_('Must be a list.'))
def validate_update_read_only(self, obj, data, value, ctx=None): value = self.to_python(obj=obj, data=data, value=value, ctx=ctx) if self.update_read_only and self.field_name in data and obj and \ getattr(obj, self.field_name) != value: raise exceptions.ValidationError( _('Field is read-only when editing.'))
def get_items_many(self, value, validate=False, ctx=None): """Create a list of referenced items. Args: value (list): The ids. Must be a list of IDS. Each ID can be a single ID or a dictionary of IDS in the case of a composite primary key. validate (boolean): Set to ``True`` if you are calling this method from the validation step. In the case of errors, a ``ValidationError`` will be raised. """ items = [] keys = self.get_primary_keys() for item in value: if not isinstance(keys, (list, tuple)): items.append(self.queryset.filter_by(**{keys: item}).first()) else: if validate: if not isinstance(item, dict): raise exceptions.ValidationError( self.MESSAGES['multikey'].format( table=self.model.__tablename__)) items.append( self.queryset.filter_by( **self.build_lookup(keys, item)).first()) return items
def validate_date(self, obj, data, value, ctx=None): if isinstance(value, datetime.date): return if isinstance(value, str): parts = value.split('-') try: datetime.date(*parts) except (TypeError, ValueError): raise exceptions.ValidationError( _('"{datestr}" does not appear' 'to be in the format "YYYY-MM-DD".').format(value)) else: raise exceptions.ValidationError( _('"{datestr}" is not a valid date.').format(value))
def validate_datetime(self, obj, data, value, ctx=None): if isinstance(value, datetime.datetime): return try: dateutil.parser.parse(value) except Exception as e: raise exceptions.ValidationError( _('Error converting datetime: {message}'.format(message=e)))
def validate_regex(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if self.regex: if not self.regex.match(value): raise exceptions.ValidationError( _('Must match the pattern "{pattern}".'.format( pattern=self.regex.pattern)))
def validate_uuid(self, obj, data, value, ctx=None): if isinstance(value, uuid.UUID): return try: uuid.UUID(value) except Exception as e: raise exceptions.ValidationError( _('Error converting uuid: {message}'.format(message=e)))
def validate_is_float(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if not isinstance(value, float): raise exceptions.ValidationError( _('"{number}" does not appear to be a float.'.format( number=value)))
def validate_field(self, obj, data, value, ctx=None): errors = [] for item in value: field_errors = self.field.validate(data=data, obj=obj, value=item, ctx=ctx) if field_errors: errors += [i for i in [e for e in field_errors]] if errors: raise exceptions.ValidationError(errors[0])
def validate_ids(self, obj, data, value, ctx=None): keys = self.get_primary_keys() retval = None if value: if self.many: retval = self.get_items_many(value, validate=True, ctx=ctx) else: retval = self.get_item_single(value, validate=True, ctx=ctx) if not retval and value: raise exceptions.ValidationError( _('A row with the key "{key}" does' ' not exist in the database.'.format(key=keys)))
def get_item_single(self, value, validate=False, ctx=None): """Get a single referenced item. Args: value (object): The id. The ID can be a single ID or a dictionary of IDS in the case of a composite primary key. validate (boolean): Set to ``True`` if you are calling this method from the validation step. In the case of errors, a ``ValidationError`` will be raised. """ item = None keys = self.get_primary_keys() if not isinstance(keys, list): item = self.queryset.filter_by(**{keys: value}).first() else: if validate: if not isinstance(value, dict): raise exceptions.ValidationError( self.MESSAGES['multikey'].format( table=self.model.__tablename__)) item = self.queryset.filter_by( **self.build_lookup(keys, value)).first() return item
def validate_choices(self, obj, data, value, ctx=None): if self.choices: if value not in self.choices: raise exceptions.ValidationError( _('"{value}" not in "{choices}"'.format( value=value, choices=', '.join(self.choices))))
def validate_read_only(self, obj, data, value, ctx=None): if self.field_name in data and self.read_only: raise exceptions.ValidationError(_('Field is read-only.'))
def validate_blank(self, obj, data, value, ctx=None): if not self.blank and value == '': raise exceptions.ValidationError(_('Cannot be blank.'))
def validate_nullable(self, obj, data, value, ctx=None): if self.required and not self.nullable and value is None: raise exceptions.ValidationError(_('Field cannot be null.'))
def validate_is_list(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if not isinstance(value, list): raise exceptions.ValidationError(_('Value must be a list.'))
def validate_is_string(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if not isinstance(value, str): raise exceptions.ValidationError(_('Must be a string.'))
def validate_max_length(self, obj, data, value, ctx=None): value = str(value) if self.max_length and len(value) > self.max_length: raise exceptions.ValidationError( _('Must be at most {chars} character(s) long.'.format( chars=self.max_length)))
def validate_regex(self, obj, data, value, ctx=None): if isinstance(value, str) and self.regex: if not self.regex.match(value): raise exceptions.ValidationError( _('"{email}" does not appear to be a valid ' 'email address.'.format(email=value)))
def validate_max_value(self, obj, data, value, ctx=None): if isinstance(value, int) and self.max_value is not None \ and value > self.max_value: raise exceptions.ValidationError( _('Value cannot be larger than {value}.'.format( value=self.max_value)))
def validate_boolean(self, obj, value, data, ctx=None): if not isinstance(value, bool): raise exceptions.ValidationError(_('Must be a boolean.'))
def validate_required(self, obj, data, value, ctx=None): if not obj and self.required and self.field_name not in data: raise exceptions.ValidationError(_('Field is required.'))