diff options
Diffstat (limited to 'rest_framework')
| -rw-r--r-- | rest_framework/authtoken/serializers.py | 6 | ||||
| -rw-r--r-- | rest_framework/exceptions.py | 9 | ||||
| -rw-r--r-- | rest_framework/fields.py | 12 | ||||
| -rw-r--r-- | rest_framework/serializers.py | 32 |
4 files changed, 34 insertions, 25 deletions
diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py index a808d0a3..f31dded1 100644 --- a/rest_framework/authtoken/serializers.py +++ b/rest_framework/authtoken/serializers.py @@ -18,13 +18,13 @@ class AuthTokenSerializer(serializers.Serializer): if user: if not user.is_active: msg = _('User account is disabled.') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) else: msg = _('Must include "username" and "password"') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) attrs['user'] = user return attrs diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index b7c2d16d..388d3dee 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -24,7 +24,14 @@ class APIException(Exception): return self.detail -class ValidationFailed(APIException): +# The recommended style for using `ValidationError` is to keep it namespaced +# under `serializers`, in order to minimize potential confusion with Django's +# built in `ValidationError`. For example: +# +# from rest_framework import serializers +# raise serializers.ValidationError('Value was invalid') + +class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST def __init__(self, detail): diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 597d5e12..2da4aa8b 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -13,7 +13,7 @@ from rest_framework.compat import ( smart_text, EmailValidator, MinValueValidator, MaxValueValidator, MinLengthValidator, MaxLengthValidator, URLValidator ) -from rest_framework.exceptions import ValidationFailed +from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import copy @@ -102,7 +102,7 @@ NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( - 'ValidationFailed raised by `{class_name}`, but error key `{key}` does ' + 'ValidationError raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' ) @@ -264,7 +264,7 @@ class Field(object): def run_validators(self, value): """ Test the given value against all the validators on the field, - and either raise a `ValidationFailed` or simply return. + and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: @@ -272,12 +272,12 @@ class Field(object): validator.serializer_field = self try: validator(value) - except ValidationFailed as exc: + except ValidationError as exc: errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: - raise ValidationFailed(errors) + raise ValidationError(errors) def validate(self, value): pass @@ -305,7 +305,7 @@ class Field(object): msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) message_string = msg.format(**kwargs) - raise ValidationFailed(message_string) + raise ValidationError(message_string) @property def root(self): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 30e6bfeb..d29dc684 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,7 +14,7 @@ from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils import six from django.utils.datastructures import SortedDict -from rest_framework.exceptions import ValidationFailed +from rest_framework.exceptions import ValidationError from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation @@ -77,13 +77,6 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): - assert not hasattr(self, 'restore_object'), ( - 'Serializer %s has old-style version 2 `.restore_object()` ' - 'that is no longer compatible with REST framework 3. ' - 'Use the new-style `.create()` and `.update()` methods instead.' % - self.__class__.__name__ - ) - validated_data = self.validated_data if kwargs: validated_data = dict( @@ -105,17 +98,24 @@ class BaseSerializer(Field): return self.instance def is_valid(self, raise_exception=False): + assert not hasattr(self, 'restore_object'), ( + 'Serializer %s has old-style version 2 `.restore_object()` ' + 'that is no longer compatible with REST framework 3. ' + 'Use the new-style `.create()` and `.update()` methods instead.' % + self.__class__.__name__ + ) + if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self._initial_data) - except ValidationFailed as exc: + except ValidationError as exc: self._validated_data = {} self._errors = exc.detail else: self._errors = {} if self._errors and raise_exception: - raise ValidationFailed(self._errors) + raise ValidationError(self._errors) return not bool(self._errors) @@ -124,6 +124,8 @@ class BaseSerializer(Field): if not hasattr(self, '_data'): if self.instance is not None and not getattr(self, '_errors', None): self._data = self.to_representation(self.instance) + elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None): + self._data = self.to_representation(self.validated_data) else: self._data = self.get_initial() return self._data @@ -329,7 +331,7 @@ class Serializer(BaseSerializer): return None if not isinstance(data, dict): - raise ValidationFailed({ + raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] }) @@ -338,8 +340,8 @@ class Serializer(BaseSerializer): self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' - except ValidationFailed as exc: - raise ValidationFailed({ + except ValidationError as exc: + raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: exc.detail }) return value @@ -359,7 +361,7 @@ class Serializer(BaseSerializer): validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) - except ValidationFailed as exc: + except ValidationError as exc: errors[field.field_name] = exc.detail except SkipField: pass @@ -367,7 +369,7 @@ class Serializer(BaseSerializer): set_value(ret, field.source_attrs, validated_value) if errors: - raise ValidationFailed(errors) + raise ValidationError(errors) return ret |
