Use invalid_data key for error message. Closes #2002.

This commit is contained in:
Tom Christie 2014-11-03 14:01:02 +00:00
parent d27b8cc09b
commit 003c42b0f5
2 changed files with 14 additions and 3 deletions

View File

@ -15,6 +15,7 @@ from django.db import models
from django.db.models.fields import FieldDoesNotExist from django.db.models.fields import FieldDoesNotExist
from django.utils import six from django.utils import six
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import ValidationError from rest_framework.exceptions import ValidationError
from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.fields import empty, set_value, Field, SkipField
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
@ -282,6 +283,10 @@ class SerializerMetaclass(type):
@six.add_metaclass(SerializerMetaclass) @six.add_metaclass(SerializerMetaclass)
class Serializer(BaseSerializer): class Serializer(BaseSerializer):
default_error_messages = {
'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.')
}
@property @property
def fields(self): def fields(self):
if not hasattr(self, '_fields'): if not hasattr(self, '_fields'):
@ -339,8 +344,11 @@ class Serializer(BaseSerializer):
return None return None
if not isinstance(data, dict): if not isinstance(data, dict):
message = self.error_messages['invalid'].format(
datatype=type(data).__name__
)
raise ValidationError({ raise ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] api_settings.NON_FIELD_ERRORS_KEY: [message]
}) })
value = self.to_internal_value(data) value = self.to_internal_value(data)

View File

@ -87,8 +87,11 @@ class TestAvoidValidation(TestCase):
def test_serializer_errors_has_only_invalid_data_error(self): def test_serializer_errors_has_only_invalid_data_error(self):
serializer = ValidationSerializer(data='invalid data') serializer = ValidationSerializer(data='invalid data')
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
self.assertDictEqual(serializer.errors, self.assertDictEqual(serializer.errors, {
{'non_field_errors': ['Invalid data']}) 'non_field_errors': [
'Invalid data. Expected a dictionary, but got unicode.'
]
})
# regression tests for issue: 1493 # regression tests for issue: 1493