From 6db3356c4d1aa4f9a042b0ec67d47238abc16dd7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 12 Sep 2014 10:21:35 +0100 Subject: [PATCH] NON_FIELD_ERRORS_KEY setting --- rest_framework/serializers.py | 8 ++++++-- rest_framework/settings.py | 1 + rest_framework/views.py | 8 +++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 502b1e190..0c2aedfa0 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -198,7 +198,9 @@ class Serializer(BaseSerializer): Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): - raise ValidationError({'non_field_errors': ['Invalid data']}) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] + }) ret = {} errors = {} @@ -224,7 +226,9 @@ class Serializer(BaseSerializer): try: return self.validate(ret) except ValidationError as exc: - raise ValidationError({'non_field_errors': exc.messages}) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: exc.messages + }) def to_representation(self, instance): """ diff --git a/rest_framework/settings.py b/rest_framework/settings.py index bbe7a56ad..f48643b5d 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -77,6 +77,7 @@ DEFAULTS = { # Exception handling 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', + 'NON_FIELD_ERRORS_KEY': 'non_field_errors', # Testing 'TEST_REQUEST_RENDERER_CLASSES': ( diff --git a/rest_framework/views.py b/rest_framework/views.py index cd394b2d9..9f08a4ad5 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -3,7 +3,7 @@ Provides an APIView class that is the base of all views in REST framework. """ from __future__ import unicode_literals -from django.core.exceptions import PermissionDenied, ValidationError +from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS from django.http import Http404 from django.utils.datastructures import SortedDict from django.views.decorators.csrf import csrf_exempt @@ -69,6 +69,12 @@ def exception_handler(exc): headers=headers) elif isinstance(exc, ValidationError): + # ValidationErrors may include the non-field key named '__all__'. + # When returning a response we map this to a key name that can be + # modified in settings. + if NON_FIELD_ERRORS in exc.message_dict: + errors = exc.message_dict.pop(NON_FIELD_ERRORS) + exc.message_dict[api_settings.NON_FIELD_ERRORS_KEY] = errors return Response(exc.message_dict, status=status.HTTP_400_BAD_REQUEST)