Python rest_framework.settings.api_settings.NON_FIELD_ERRORS_KEY Examples

The following are 13 code examples of rest_framework.settings.api_settings.NON_FIELD_ERRORS_KEY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.settings.api_settings , or try the search function .
Example #1
Source File: validation.py    From django-rest-registration with MIT License 6 votes vote down vote up
def run_validators(validators: Iterable[Validator], value: Any) -> None:
    fields_errors = OrderedDict()  # type: Dict[str, Any]
    non_field_errors = []  # type: List[Any]
    for validator in validators:
        try:
            validator(value)
        except ValidationError as exc:
            if isinstance(exc.detail, Mapping):
                for field_name, field_errors in exc.detail.items():
                    fields_errors.setdefault(field_name, []).extend(
                        field_errors)
            elif isinstance(exc.detail, list):
                non_field_errors.extend(exc.detail)

    if fields_errors:
        errors = {}
        errors.update(fields_errors)
        errors.setdefault(
            api_settings.NON_FIELD_ERRORS_KEY, []).extend(non_field_errors)
        raise ValidationError(errors)
    if non_field_errors:
        # TODO: Issue #109 - remove type: ignore
        raise ValidationError(non_field_errors)  # type: ignore 
Example #2
Source File: utils.py    From Django-Styleguide with MIT License 6 votes vote down vote up
def _get_response_json_from_drf_errors(self, serializer_errors=None):
        if serializer_errors is None:
            serializer_errors = {}

        if type(serializer_errors) is list:
            serializer_errors = {
                api_settings.NON_FIELD_ERRORS_KEY: serializer_errors
            }

        list_of_errors = self._get_list_of_errors(errors_dict=serializer_errors)

        response_data = {
            self.ERRORS: list_of_errors
        }

        return response_data 
Example #3
Source File: serializers.py    From edx-enterprise with GNU Affero General Public License v3.0 6 votes vote down vote up
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 not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise serializers.ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            })

        ret = []

        for item in data:
            try:
                validated = self.child.run_validation(item)
            except serializers.ValidationError as exc:
                ret.append(exc.detail)
            else:
                ret.append(validated)

        return ret 
Example #4
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def as_serializer_error(exc):
    assert isinstance(exc, (ValidationError, DjangoValidationError))

    if isinstance(exc, DjangoValidationError):
        detail = get_error_detail(exc)
    else:
        detail = exc.detail

    if isinstance(detail, Mapping):
        # If errors may be a dict we use the standard {key: list of values}.
        # Here we ensure that all the values are *lists* of errors.
        return {
            key: value if isinstance(value, (list, Mapping)) else [value]
            for key, value in detail.items()
        }
    elif isinstance(detail, list):
        # Errors raised as a list are non-field errors.
        return {
            api_settings.NON_FIELD_ERRORS_KEY: detail
        }
    # Errors raised as a string are non-field errors.
    return {
        api_settings.NON_FIELD_ERRORS_KEY: [detail]
    } 
Example #5
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
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 #6
Source File: views.py    From django-pushy with MIT License 5 votes vote down vote up
def _not_found_response(self, key):
        errors_key = api_settings.NON_FIELD_ERRORS_KEY

        return Response(data={
            errors_key: ['Key {} was not found'.format(key)]
        }, status=status.HTTP_404_NOT_FOUND) 
Example #7
Source File: serializers.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
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 not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise serializers.ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            })

        ret = []

        for item in data:
            try:
                validated = self.child.run_validation(item)
            except serializers.ValidationError as exc:
                ret.append(
                    {
                        'non_field_errors': [{
                            'code': item.get('code'),
                            'email': item.get('email'),
                            'detail': 'failure',
                            'message': exc.detail['non_field_errors'][0]
                        }]
                    }
                )
            else:
                ret.append(validated)

        return ret 
Example #8
Source File: serializers.py    From silver with Apache License 2.0 5 votes vote down vote up
def django_to_drf_validation_error(django_validation_error,
                                   default_errors_key=None):
    try:
        errors = django_validation_error.message_dict
    except AttributeError:
        errors = django_validation_error.messages
        if default_errors_key:
            errors = {default_errors_key: errors}
    else:
        non_field_errors = errors.pop(NON_FIELD_ERRORS, None)
        if non_field_errors:
            errors[default_errors_key or api_settings.NON_FIELD_ERRORS_KEY] = non_field_errors

    raise serializers.ValidationError(errors) 
Example #9
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def to_internal_value(self, data):
        """
        Dict of native values <- Dict of primitive datatypes.
        """
        if not isinstance(data, Mapping):
            message = self.error_messages['invalid'].format(
                datatype=type(data).__name__
            )
            raise ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            }, code='invalid')

        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 DjangoValidationError as exc:
                errors[field.field_name] = get_error_detail(exc)
            except SkipField:
                pass
            else:
                set_value(ret, field.source_attrs, validated_value)

        if errors:
            raise ValidationError(errors)

        return ret 
Example #10
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def errors(self):
        ret = super(Serializer, self).errors
        if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
            # Edge case. Provide a more descriptive error than
            # "this field may not be null", when no data is passed.
            detail = ErrorDetail('No data provided', code='null')
            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
        return ReturnDict(ret, serializer=self)


# There's some replication of `ListField` here,
# but that's probably better than obfuscating the call hierarchy. 
Example #11
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
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:
                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 #12
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def errors(self):
        ret = super(ListSerializer, self).errors
        if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
            # Edge case. Provide a more descriptive error than
            # "this field may not be null", when no data is passed.
            detail = ErrorDetail('No data provided', code='null')
            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
        if isinstance(ret, dict):
            return ReturnDict(ret, serializer=self)
        return ReturnList(ret, serializer=self)


# ModelSerializer & HyperlinkedModelSerializer
# -------------------------------------------- 
Example #13
Source File: utils.py    From Django-Styleguide with MIT License 4 votes vote down vote up
def _get_list_of_errors(self, field_path='', errors_dict=None):
        """
        Error_dict is in the following format:
        {
            'field1': {
                'message': 'some message..'
                'code' 'some code...'
            },
            'field2: ...'
        }
        """
        if errors_dict is None:
            return []

        message_value = errors_dict.get(self.MESSAGE, None)

        # Note: If 'message' is name of a field we don't want to stop the recursion here!
        if message_value is not None and\
           (type(message_value) in {str, exceptions.ErrorDetail}):
            if field_path:
                errors_dict[self.FIELD] = field_path
            return [errors_dict]

        errors_list = []
        for key, value in errors_dict.items():
            new_field_path = '{0}.{1}'.format(field_path, key) if field_path else key
            key_is_non_field_errors = key == api_settings.NON_FIELD_ERRORS_KEY

            if type(value) is list:
                current_level_error_list = []
                new_value = value

                for error in new_value:
                    # if the type of field_error is list we need to unpack it
                    field_error = self._unpack(error)

                    if not key_is_non_field_errors:
                        field_error[self.FIELD] = new_field_path

                    current_level_error_list.append(field_error)
            else:
                path = field_path if key_is_non_field_errors else new_field_path

                current_level_error_list = self._get_list_of_errors(field_path=path, errors_dict=value)

            errors_list += current_level_error_list

        return errors_list