def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise ValidationError({
                api_settings.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 to_internal_value(self, data):
     """
     List of dicts of native values <- List of dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_list(data)
     return [self.child.run_validation(item) for item in data]
 def get_value(self, dictionary):
     """
     Given the input dictionary, return the field value.
     """
     # We override the default field access in order to support
     # lists in HTML forms.
     if html.is_html_input(dictionary):
         return html.parse_html_list(dictionary, prefix=self.field_name)
     return dictionary.get(self.field_name, empty)
 def to_internal_value(self, data):
     """
     List of dicts of native values <- List of dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_list(data)
     if isinstance(data, type('')) or not hasattr(data, '__iter__'):
         self.fail('not_a_list', input_type=type(data).__name__)
     return [self.child.run_validation(item) for item in data]
 def get_value(self, dictionary):
     # We override the default field access in order to support
     # lists in HTML forms.
     if html.is_html_input(dictionary):
         return html.parse_html_list(dictionary, prefix=self.field_name)
     value = dictionary.get(self.field_name, empty)
     #if isinstance(value, type('')):
     #    return json.loads(value)
     return value
 def to_internal_value(self, data):
     """
     List of dicts of native values <- List of dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_list(data)
     if isinstance(data, type('')) or not hasattr(data, '__iter__'):
         self.fail('not_a_list', input_type=type(data).__name__)
     return [self.child.run_validation(item) for item in data]
Exemple #7
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if not self.instance:
            return super().to_internal_value(data)

        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            if self.parent and self.partial:
                raise SkipField()

            message = self.error_messages['empty']
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='empty')

        ret = []
        errors = []

        for item in data:
            try:
                # prepare child serializer to only handle one instance
                if 'id' in item:
                    pk = item["id"]
                elif 'pk' in item:
                    pk = item["pk"]
                else:
                    raise ValidationError("id or pk not in data")
                child = self.instance.get(id=pk) if self.instance else None
                self.child.instance = child
                self.child.initial_data = item
                # raw
                validated = self.child.run_validation(item)
            except ValidationError as exc:
                errors.append(exc.detail)
            except ObjectDoesNotExist as e:
                errors.append(e)
            else:
                ret.append(validated)
                errors.append({})

        if any(errors):
            raise ValidationError(errors)

        return ret
Exemple #8
0
 def to_internal_value(self, data):
     if html.is_html_input(data):
         data = html.parse_html_list(data)
     if isinstance(data, type("")) or isinstance(
             data, Mapping) or not hasattr(data, "__iter__"):
         self.fail("not_a_list", input_type=type(data).__name__)
     if not self.allow_empty and len(data) == 0:
         self.fail("empty")
     # Begin code retained from < drf 3.8.x.
     return [self.child.run_validation(item) for item in data]
 def get_value(self, dictionary):
     if self.field_name not in dictionary:
         if getattr(self.root, 'partial', False):
             return empty
     # We override the default field access in order to support
     # lists in HTML forms.
     if html.is_html_input(dictionary):
         val = dictionary.getlist(self.field_name, [])
         if len(val) > 0:
             # Support QueryDict lists in HTML input.
             return val
         return html.parse_html_list(dictionary, prefix=self.field_name)
     return dictionary.getlist(self.field_name, empty)
Exemple #10
0
 def to_internal_value(self, data):
     """
     List of dicts of native values <- List of dicts of primitive datatypes.
     """
     _data = data[0].split(',') if len(data) > 0 else data
     if html.is_html_input(_data):
         data = html.parse_html_list(_data)
     if isinstance(_data, type('')) or isinstance(
             _data, collections.Mapping) or not hasattr(data, '__iter__'):
         self.fail('not_a_list', input_type=type(_data).__name__)
     if not self.allow_empty and len(_data) == 0:
         self.fail('empty')
     return [self.child.run_validation(item) for item in _data]
    def to_internal_value(self, data):
        """
        Data transformation to python list object.

        :param object data: Data for transformation.

        :return: Transformed data.
        :rtype: list

        :raise ValidationError: If data not valid.

        """
        # Parse data.
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        # Initial validation that came in an array.
        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(detail={'non_field_errors': [message]},
                                  code='not_a_list')

        # Validation that this is not an empty value and whether it is empty.
        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError(detail={'non_field_errors': [message]},
                                  code='empty')

        res, errors = [], []  # Make storage for results.

        # Validating each item from the list.
        for item in data:
            try:
                value = self.child.run_validation(item)
            except ValidationError as e:
                res.append({})
                errors.append(e.detail)
            else:
                res.append(value)
                errors.append({})

        # If the conversion and validation failed.
        if any(errors):
            raise ValidationError(detail=errors)

        # We return the transformed and validated data.
        return res
Exemple #12
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            if self.parent and self.partial:
                raise SkipField()

            message = self.error_messages['empty']
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='empty')

        ret = []
        errors = []

        for item in data:
            try:
                # prepare child serializer to only handle one instance
                if 'id' in item.keys():
                    self.child.instance = self.instance.get(id=item['id']) if self.instance else None
                if 'pk' in item.keys():
                    self.child.instance = self.instance.get(id=item['pk']) if self.instance else None

                self.child.initial_data = item
                # raw
                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 to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """

        serializer_field = self.fields[self.model_field.name]

        if html.is_html_input(data):
            data = html.parse_html_list(data)
        if isinstance(data, type('')) or not hasattr(data, '__iter__'):
            self.fail('not_a_dict', input_type=type(data).__name__)

        native = OrderedDict()
        for key in data:
            native[key] = serializer_field.run_validation(data[key])
        return native
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]},
                code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            if self.parent and self.partial:
                raise SkipField()

            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='empty')

        id_attr = getattr(self.child.Meta, 'update_lookup_field', 'id')
        ret = []
        errors = []

        for item in data:
            try:
                view = self.context.get('view')
                if view and view.action != 'create':
                    if id_attr not in item:
                        raise ValidationError(
                            {id_attr: ['This field is required.']})

                    instance = self.instance.get(**{id_attr: item[id_attr]})

                    self.child.instance = instance
                    self.child.initial_data = item
                # Until here
                validated = self.child.run_validation(item)
            except ValidationError as exc:
                errors.append(exc.detail)
            else:
                ret.append(validated)
                errors.append({})

        return {'ret': ret, 'errors': errors}
Exemple #15
0
    def to_internal_value(self, data):
        """
        各个数据放入子序列化器中验证
        """
        # 解析 html 输入数据
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        # 确认数据是列表
        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]},
                code='not_a_list')

        # 确认非允许空的情况下数据不为空
        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='empty')

        # 将各个数据放入子序列化器中验证
        ret = []
        errors = []
        for item in data:
            try:
                # 区分是否当前是否为更新操作
                if self.instance is not None:
                    view = self.context.get('view')
                    id_attr = view.lookup_url_kwarg or view.lookup_field
                    instance = self.instance.get(**{id_attr: item[id_attr]})
                    self.child.instance = instance
                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)

        # 还原子序列化器对象的 instance 属性
        self.child.instance = self.instance

        return ret
Exemple #16
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data, default=[])

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]},
                code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            if self.parent and self.partial:
                raise SkipField()

            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='empty')

        ret = []
        errors = []

        for item in data:
            try:
                if self.instance:
                    try:
                        self.child.instance = self.instance.get(id=item['id'])
                        self.child.initial_data = item
                    except getattr(self.child.Meta.model,
                                   'DoesNotExist') as exc:
                        raise ValidationError({'non_field_errors': [str(exc)]})

                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
Exemple #17
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        Modified from https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py
        based on suggestions from https://github.com/miki725/django-rest-framework-bulk/issues/68
        This is to prevent an error whereby the DRF Unique validator fails when the instance on the child
        serializer is a queryset and not an object.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data, default=[])

        if not isinstance(data, list):
            message = self.error_messages["not_a_list"].format(
                input_type=type(data).__name__
            )
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="not_a_list"
            )

        if not self.allow_empty and len(data) == 0:
            message = self.error_messages["empty"]
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="empty"
            )

        ret = []
        errors = []

        data_lookup = self._data_lookup_dict()

        for item in data:
            try:
                # prepare child serializer to only handle one instance
                self.child.instance = data_lookup.get(self.child.id_value_lookup(item))
                self.child.initial_data = item
                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
Exemple #18
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]})

        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]})

        result = []
        errors = []
        id_attrs = self.get_id_attrs()
        for item in data:
            error = {}
            for id_attr in id_attrs:
                if id_attr in item:
                    try:
                        self.child.instance = self.instance.get(
                            **{id_attr: item[id_attr]
                               }) if self.instance else None
                    except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
                        error.update({id_attr: [str(e)]})
                    break
            if not error:
                try:
                    # Do validation
                    validated = self.child.run_validation(item)
                except ValidationError as exc:
                    error = exc.detail
                else:
                    result.append(validated)
            errors.append(error)

        if any(errors):
            del self.initial_data
            raise ValidationError(errors)
        return result
Exemple #19
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data, default=[])

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]},
                code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            if self.parent and self.partial:
                raise SkipField()

            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='empty')

        ret = []
        errors = []

        id_attr = getattr(self.child.Meta, 'update_lookup_field', 'id')

        for item in data:
            try:
                # --------------------- patched pieces --------------------------------
                self.child.instance = self.instance.get(
                    **{id_attr: item.get(id_attr)})
                self.child.initial_data = item
                # ---------------------------------------------------------------------
                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
Exemple #20
0
    def to_internal_value(self, data):
        """
        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,
        processing for other items that did not fail will continue.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data, default=[])

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]},
                code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='empty')

        ret = []
        errors = []

        for item in data:
            try:
                validated = self.child.run_validation(item)
            except ValidationError as exc:
                # this adds the type ErrorDetail to the validated data if it's a unique error
                # it will be removed in the create function so we can count the unique errors and log them
                if "path" in exc.detail.keys(
                ) and exc.detail["path"][0].code == "unique":
                    ret.append(exc.detail)
                # other ValidationErrors will be processes as they would be normally
                else:
                    errors.append(exc.detail)
            else:
                ret.append(validated)
                errors.append({})

        if any(errors):
            raise ValidationError(errors)

        return ret
    def to_internal_value(self, data):
        """
        Data transformation to python list object.

        :param iter data: Data for transformation.

        :return: Transformed data.
        :rtype: list

        :raise ValidationError: If not valid data.

        """
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        if any((isinstance(data, type('')), isinstance(data, Mapping), not hasattr(data, '__iter__'))):
            self.fail('not_a_list', input_type=type(data).__name__)

        if not self.allow_empty and len(data) == 0:
            self.fail('empty')

        return [self.child.run_validation(item) for item in data]
Exemple #22
0
    def to_internal_value(self, data):
        """
        List of dicts of native values <- List of dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_list(data, default=[])

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='not_a_list')

        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='empty')

        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 self.token.join(str(r) for r in ret)
Exemple #23
0
 def get_value(self, dictionary):
     # We override the default field access in order to support
     # lists in HTML forms.
     if html.is_html_input(dictionary):
         return html.parse_html_list(dictionary, prefix=self.field_name)
     return dictionary.get(self.field_name, empty)