Example #1
0
 def get_value(self, dictionary):
     # We override the default field access in order to support
     # nested HTML forms.
     if html.is_html_input(dictionary):
         return html.parse_html_dict(dictionary,
                                     prefix=self.field_name) or empty
     return dictionary.get(self.field_name, empty)
Example #2
0
 def to_internal_value(self, data):
     """
     Range instances <- Dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail('not_a_dict', input_type=type(data).__name__)
     validated_dict = {}
     for key in ('lower', 'upper'):
         try:
             value = data.pop(key)
         except KeyError:
             continue
         validated_dict[six.text_type(key)] = self.child.run_validation(
             value)
     for key in ('bounds', 'empty'):
         try:
             value = data.pop(key)
         except KeyError:
             continue
         validated_dict[six.text_type(key)] = value
     if data:
         self.fail('too_much_content',
                   extra=', '.join(map(str, data.keys())))
     return self.range_type(**validated_dict)
    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
Example #4
0
    def to_internal_value(self, data):
        """
        Range instances <- Dicts of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_dict(data)

        if not isinstance(data, dict):
            self.fail('not_a_dict', input_type=type(data).__name__)

        extra_content = list(
            set(data) - set(["lower", "upper", "bounds", "empty"]))
        if extra_content:
            self.fail('too_much_content',
                      extra=', '.join(map(str, extra_content)))

        validated_dict = {}
        for key in ('lower', 'upper'):
            try:
                value = data[key]
            except KeyError:
                continue

            validated_dict[str(key)] = self.child.run_validation(value)

        for key in ('bounds', 'empty'):
            try:
                value = data[key]
            except KeyError:
                continue

            validated_dict[str(key)] = value

        return self.range_type(**validated_dict)
    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]
Example #7
0
 def to_internal_value(self, data):
     """Dicts of native values <- Dicts of primitive datatypes."""
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail("not_a_dict", input_type=type(data).__name__)
     return self.run_child_validation(data)
Example #8
0
	def get_value(self, dictionary):
		if html.is_html_input(dictionary): # NOTE: with form/urlencoded we get [u'opt,opt'] for some reason, gotta work around
			try:
				return dictionary.getlist(self.field_name)[0]
			except IndexError:
				return super(MultiSelectField, self).get_value(dictionary)
		else:
			return super(MultiSelectField, self).get_value(dictionary)
Example #9
0
 def get_value(self, dictionary):
     # We override the default field access in order to support
     # nested HTML forms.
     if html.is_html_input(dictionary):
         return html.parse_html_dict(
             dictionary, prefix=self.field_name
         ) or empty
     return dictionary.get(self.field_name, empty)
Example #10
0
 def get_value(self, dictionary):
     """
     Override the default field access in order to support dictionaries in
     HTML forms.
     """
     if html.is_html_input(dictionary):
         return html.parse_html_dict(dictionary, prefix=self.field_name)
     return dictionary.get(self.field_name, serializers.empty)
Example #11
0
 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):
         return dictionary.getlist(self.field_name)
     return dictionary.get(self.field_name, empty)
 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
Example #13
0
 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 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)
Example #15
0
 def to_internal_value(self, data):
     if html.is_html_input(data):
         data = html.parse_html_list(data, default=[])
     if isinstance(data, (str, 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]
Example #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)
     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 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]
Example #18
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
Example #19
0
 def get_value(self, dictionary):
     if html.is_html_input(
             dictionary
     ):  # NOTE: with form/urlencoded we get [u'opt,opt'] for some reason, gotta work around
         try:
             return dictionary.getlist(self.field_name)[0]
         except IndexError:
             return super(MultiSelectField, self).get_value(dictionary)
     else:
         return super(MultiSelectField, self).get_value(dictionary)
Example #20
0
 def to_internal_value(self, data):
     """
     Dicts of native values <- Dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail('not_a_dict', input_type=type(data).__name__)
     return dict([(six.text_type(key), self.child.run_validation(value))
                  for key, value in data.items()])
Example #21
0
 def get_value(self, dictionary):
     """
     Given the *incoming* primitive data, return the value for this field
     that should be validated and transformed to a native value.
     """
     if html.is_html_input(dictionary):
         # HTML forms will represent empty fields as '', and cannot
         # represent None or False values directly.
         ret = dictionary.get(self.field_name, '')
         return self.default_empty_html if (ret == '') else ret
     return dictionary.get(self.field_name, empty)
Example #22
0
 def get_value(self, dictionary):
     """
     Given the *incoming* primitive data, return the value for this field
     that should be validated and transformed to a native value.
     """
     if html.is_html_input(dictionary):
         # HTML forms will represent empty fields as '', and cannot
         # represent None or False values directly.
         ret = dictionary.get(self.field_name, '')
         return self.default_empty_html if (ret == '') else ret
     return dictionary.get(self.field_name, empty)
Example #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):
            # Don't return [] if the update is partial
            if self.field_name not in dictionary:
                if getattr(self.root, 'partial', False):
                    return empty
            return dictionary.getlist(self.field_name)

        return dictionary.get(self.field_name, empty)
Example #24
0
 def to_internal_value(self, data):
     """
     Ensure incoming data is a dictionary and run validation on entries.
     """
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail("not_a_dict", input_type=type(data).__name__)
     if not self.allow_empty and len(data) == 0:
         self.fail("empty")
     return self.run_child_validation(data)
Example #25
0
    def get_value(self, dictionary):
        if html.is_html_input(dictionary) and self.field_name in dictionary:
            # When HTML form input is used, mark up the input
            # as being a JSON string, rather than a JSON primitive.
            class JSONString(six.text_type):
                def __new__(self, value):
                    ret = six.text_type.__new__(self, value)
                    ret.is_json_string = True
                    return ret

            return JSONString(dictionary[self.field_name])
        return dictionary.get(self.field_name, serializers.empty)
 def to_internal_value(self, data):
     """
     Dicts of native values <- Dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail('not_a_dict', input_type=type(data).__name__)
     return dict([
         (six.text_type(key), self.child.run_validation(value))
         for key, value in data.items()
     ])
Example #27
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 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)
Example #29
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):
        """
        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
    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}
Example #33
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
Example #34
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
Example #35
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
Example #36
0
    def to_internal_value(self, data):
        """
        Dicts of native values <- Dicts of primitive datatypes.
        """

        if html.is_html_input(data):
            data = html.parse_html_dict(data)
        if not isinstance(data, dict):
            self.fail('not_a_dict', input_type=type(data).__name__)
        if not self.allow_empty and len(data.keys()) == 0:
            message = self.error_messages['empty']
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]})
        return {
            str(key): self.child.run_validation(value)
            for key, value in data.items()
        }
Example #37
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
Example #38
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
Example #39
0
def validate_field_value(wrapped, instance, args, kwargs):
    """验证字段数据"""
    field = args[0]
    data = args[1]

    if html.is_html_input(data):
        if field.field_name not in data:
            if getattr(field.root, 'partial', False):
                return empty
            return field.default_empty_html

        ret = wrapped(*args, **kwargs)
        if ret == '' and field.allow_null:
            return '' if getattr(field, 'allow_blank', False) else None
        elif ret == '' and not field.required:
            return '' if getattr(field, 'allow_blank', False) else empty
        return ret
    return wrapped(*args, **kwargs)
Example #40
0
 def get_value(self, dictionary):
     """
     Given the *incoming* primitive data, return the value for this field
     that should be validated and transformed to a native value.
     """
     if html.is_html_input(dictionary):
         # HTML forms will represent empty fields as '', and cannot
         # represent None or False values directly.
         if self.field_name not in dictionary:
             if getattr(self.root, 'partial', False):
                 return empty
             return self.default_empty_html
         ret = dictionary[self.field_name]
         if ret == '' and self.allow_null:
             # If the field is blank, and null is a valid value then
             # determine if we should use null instead.
             return '' if getattr(self, 'allow_blank', False) else None
         return ret
     return dictionary.get(self.field_name, empty)
 def get_value(self, dictionary):
     """
     Given the *incoming* primitive data, return the value for this field
     that should be validated and transformed to a native value.
     """
     if html.is_html_input(dictionary):
         # HTML forms will represent empty fields as '', and cannot
         # represent None or False values directly.
         if self.field_name not in dictionary:
             if getattr(self.root, 'partial', False):
                 return empty
             return self.default_empty_html
         ret = dictionary[self.field_name]
         if ret == '' and self.allow_null:
             # If the field is blank, and null is a valid value then
             # determine if we should use null instead.
             return '' if getattr(self, 'allow_blank', False) else None
         return ret
     return dictionary.get(self.field_name, empty)
Example #42
0
    def to_internal_value(self, data):
        """
        Range instances <- Lists of primitive datatypes.
        """
        if html.is_html_input(data):
            data = html.parse_html_dict(data)
        if not isinstance(data, (list, tuple,)):
            self.fail('not_a_list', input_type=type(data).__name__)
        validated_dict = {}
        for field in ('lower', 'upper',):
            try:
                validated_dict[field] = self.child.run_validation(data.pop(0))
            except:
                validated_dict[field] = None
        try:
            validated_dict['bounds'] = data.pop(0)
        except IndexError:
            pass

        if data:
            self.fail('too_much_content', extra=', '.join(map(str, data)))

        return self.range_type(**validated_dict)
Example #43
0
 def to_internal_value(self, data):
     """
     Range instances <- Dicts of primitive datatypes.
     """
     if html.is_html_input(data):
         data = html.parse_html_dict(data)
     if not isinstance(data, dict):
         self.fail('not_a_dict', input_type=type(data).__name__)
     validated_dict = {}
     for key in ('lower', 'upper'):
         try:
             value = data.pop(key)
         except KeyError:
             continue
         validated_dict[six.text_type(key)] = self.child.run_validation(value)
     for key in ('bounds', 'empty'):
         try:
             value = data.pop(key)
         except KeyError:
             continue
         validated_dict[six.text_type(key)] = value
     if data:
         self.fail('too_much_content', extra=', '.join(map(str, data.keys())))
     return self.range_type(**validated_dict)
Example #44
0
 def get_value(self, dictionary):
     if html.is_html_input(dictionary):
         content = dictionary.get(self.field_name, [''])
         return [x.strip() for x in content.splitlines() if x.strip()]
     return dictionary.get(self.field_name, [])
 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 dictionary.getlist(self.field_name)
     return dictionary.get(self.field_name, empty)
Example #46
0
 def to_internal_value(self, data):
     if html.is_html_input(data):
         data = parse_json_form(data)
     return super(JSONFormSerializer, self).to_internal_value(data)
Example #47
0
def html_safe_get(obj, key, default=None):
    if html.is_html_input(obj):
        return obj.getlist(key, default)
    return obj.get(key, default)
Example #48
0
 def get_value(self, dictionary):
     if html.is_html_input(dictionary):
         return dictionary.getlist(self.field_name)
     return dictionary.get(self.field_name, None)