def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if not isinstance(data, list): message = self.error_messages['not_a_list'].format( input_type=type(data).__name__ ) raise ValidationError({ settings.REST_CONFIG['NON_FIELD_ERRORS_KEY']: [message] }) if not self.allow_empty and len(data) == 0: message = self.error_messages['empty'] raise ValidationError({ settings.REST_CONFIG['NON_FIELD_ERRORS_KEY']: [message] }) ret = [] errors = [] for item in data: try: validated = self.child.run_validation(item) except ValidationError as exc: errors.append(exc.detail) else: ret.append(validated) errors.append({}) if any(errors): raise ValidationError(errors) return ret
def test_function_returns_dict_for_exception_with_message_as_string(self): message = '@ must be in email address' exc = ValidationError('expected message') exc.detail = message # someone patched object detail = get_validation_error_detail(exc) self.assertIsInstance(detail, dict) self.assertIn('non_field_errors', detail.keys()) self.assertIsInstance(detail['non_field_errors'], list) self.assertEqual(len(detail['non_field_errors']), 1) self.assertEqual(detail['non_field_errors'][0], message)
def post(self, request, *args, **kwargs): if not request.data: raise ValidationError('You must provide arguments for create.') if not isinstance(request.data, list): raise ValidationError('You must provide a list of objects.') serializer = UserSerializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) serializer.save() return serializer.data
def put(self, request, id, *args, **kwargs): if not request.data: raise ValidationError('You must provide an updated instance.') session = settings.SQLALCHEMY_SESSION() instance = session.query(User).filter(User.id == id).first() if not instance: raise ValidationError('Object does not exist') serializer = UserSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return serializer.data
def get_manufacturer(self, name): try: manufacturer = Manufacturer.objects.get(name__iexact=name) except ObjectDoesNotExist: raise ValidationError("The requested object does not exist") return manufacturer
def run_validation(self, data=empty): """ We override the default `run_validation`, because the validation performed by validators and the `.validate()` method should be coerced into an error dictionary with a 'non_fields_error' key. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data for field in self.fields.values(): for validator in field.validators: if hasattr(validator, 'set_context'): validator.set_context(field) value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the ' \ 'validated data' except (ValidationError, DjangoValidationError) as exc: raise ValidationError(detail=get_validation_error_detail(exc)) return value
def get_car(self, name): try: car = Car.objects.get(name__iexact=name) except ObjectDoesNotExist: raise ValidationError("The requested object does not exist") return car
def __call__(self, value): try: self.validator_func(self.model_field, self.field_name, value) except AssertionError as exc: message = exc.args[0] if exc.args else self.message.format( field=self.field_name, value=value) raise ValidationError(message)
def post(self, request, *args, **kwargs): if not request.data: raise ValidationError('You must provide arguments for create.') serializer = CarSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return serializer.data
def test_function_returns_dict_for_exception_with_message_as_dict(self): message = {'email': '@ must be in email address'} exc = ValidationError(message) detail = get_validation_error_detail(exc) self.assertIsInstance(detail, dict) self.assertIn('email', detail.keys()) self.assertEqual(detail['email'][0], message['email'])
def put(self, request, name, *args, **kwargs): if not request.data: raise ValidationError('You must provide data for update.') instance = self.get_car(name) serializer = CarSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return serializer.data
def put(self, request, name, *args, **kwargs): if not request.data: raise ValidationError('You must provide arguments for create.') instance = self.get_manufacturer(name) serializer = ManufacturerSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return serializer.data
def test_function_returns_dict_for_exception_with_message_as_list(self): message = ['@ must be in email address', ] exc = ValidationError(message) detail = get_validation_error_detail(exc) self.assertIsInstance(detail, dict) self.assertIn('non_field_errors', detail.keys()) self.assertIsInstance(detail['non_field_errors'], list) self.assertEqual(len(detail['non_field_errors']), 1) self.assertEqual(detail['non_field_errors'], message)
def __call__(self, value): session = self._get_session() try: queryset = session.query(self.model) queryset = self.filter_queryset(value, queryset) queryset = self.exclude_current_instance(queryset) if session.query(queryset.exists()).scalar(): raise ValidationError(self.message) finally: session.close()
def run_validators(self, value): """ Check the given value through all validators for the specified field. :param value: value, required for processing. """ errors = [] for validator in self.validators: try: validator(value) except ValidationError as exc: errors.extend(exc.detail) if errors: raise ValidationError(errors)
def raise_error(self, key, **kwargs): """ Helper function, that raise validation error with taken message. :param key: key for dictionary, by which selected concrete message. :param kwargs: dictionary object, which store additional arguments. """ try: msg = self.error_messages[key] except KeyError: msg = ERROR_MESSAGE_NOT_FOUND.format(key=key) raise AssertionError(msg) message = msg.format(**kwargs) raise ValidationError(message)
def run_validation(self, data=empty): (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' # NOQA except (ValidationError, AssertionError) as exc: raise ValidationError(detail=get_validation_error_detail(exc)) return value
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ settings.REST_CONFIG['NON_FIELD_ERRORS_KEY']: [message] }) ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr( self, 'validate_' + field.field_name, None ) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def run_validation(self, data=empty): """ We override the default `run_validation`, because the validation performed by validators and the `.validate()` method should be coerced into an error dictionary with a 'non_fields_error' key. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' # NOQA except (ValidationError, AssertionError) as exc: raise ValidationError(detail=get_validation_error_detail(exc)) return value
def is_valid(self, raise_exception=False): assert hasattr(self, 'initial_data'), ( 'Cannot call `.is_valid()` as no `data=` keyword argument was ' 'passed when instantiating the serializer instance.' ) if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self.initial_data) except ValidationError as exc: self._validated_data = {} self._errors = exc.detail else: self._errors = {} if self._errors and raise_exception: raise ValidationError(self.errors) return not bool(self._errors)
def update(self, instance, validated_data): raise_errors_on_nested_writes('update', self, validated_data) ModelClass = self.Meta.model relations = model_meta.get_relations_data(ModelClass, validated_data) # Generate filter for getting existing object once more. Earlier, # We generate query to the database, because we can get relationship # objects, which attached to the existing object. But can't use this # instance further. To avoid issues with it, just get object once more filter_args = (getattr(ModelClass, field) == getattr(instance, field) for field in model_meta.model_pk(ModelClass)) # Simply set each attribute on the instance, and then save it. # Note that unlike `.create()` we don't need to treat many-to-many # relationships as being a special case. During updates we already # have an instance pk for the relationships to be associated with session = settings.SQLALCHEMY_SESSION(expire_on_commit=False) try: instance = session.query(ModelClass).filter(*filter_args).first() if not instance: raise ValidationError("Object does not exist.") for field_name, value in validated_data.items(): setattr(instance, field_name, value) # Update relation objects if relations: session.enable_relationship_loading(instance) for field_name, value in relations.items(): setattr(instance, field_name, []) session.refresh(instance) if value: setattr(instance, field_name, value) session.commit() finally: session.close() return instance
def __call__(self, value): if self.max_length and len(value) > self.max_length: message = self.message.format(max_length=self.max_length) raise ValidationError(message)
def __call__(self, value): if value < self.min_value: message = self.message.format(min_value=self.min_value) raise ValidationError(message)
def __call__(self, value): if not self.is_enum_key(value): message = self.message.format(key_list=self.keys) raise ValidationError(message)
def __call__(self, value): queryset = self.queryset queryset = self.filter_queryset(value, queryset) queryset = self.exclude_current_instance(queryset) if qs_exists(queryset): raise ValidationError(self.message)
def __call__(self, data): if data['name'] == 'admin': raise ValidationError("Permission denied.")
def __call__(self, data): for obj in data: if obj['pk'] < 0: raise ValidationError("PKs can't be negative.")
def __call__(self, data): if data['name'] == 'test': raise ValidationError("Invalid author name.")
def __call__(self, value): raise ValidationError("error")