@@ -144,11 +144,15 @@ The corresponding code would now look like this:
...
@@ -144,11 +144,15 @@ The corresponding code would now look like this:
logging.info('Creating ticket "%s"' % name)
logging.info('Creating ticket "%s"' % name)
serializer.save(user=request.user) # Include the user when saving.
serializer.save(user=request.user) # Include the user when saving.
#### Use `rest_framework.exceptions.ValidationFailed`.
#### Using `serializers.ValidationError`.
Django's `ValidationError` class is intended for use with HTML forms and it's API makes its use slightly awkward with nested validation errors as can occur in serializers.
Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class.
We now include a simpler `ValidationFailed` exception class in REST framework that you should use when raising validation failures.
The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you are always using the `serializers.ValidationError` exception class, and not Django's built-in exception.
We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion.
#### Change to `validate_<field_name>`.
#### Change to `validate_<field_name>`.
...
@@ -156,14 +160,14 @@ The `validate_<field_name>` method hooks that can be attached to serializer clas
...
@@ -156,14 +160,14 @@ The `validate_<field_name>` method hooks that can be attached to serializer clas
def validate_score(self, attrs, source):
def validate_score(self, attrs, source):
if attrs[score] % 10 != 0:
if attrs[score] % 10 != 0:
raise ValidationError('This field should be a multiple of ten.')
raise serializers.ValidationError('This field should be a multiple of ten.')
return attrs
return attrs
This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value.
This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value.
def validate_score(self, value):
def validate_score(self, value):
if value % 10 != 0:
if value % 10 != 0:
raise ValidationError('This field should be a multiple of ten.')
raise serializers.ValidationError('This field should be a multiple of ten.')
return value
return value
Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.
Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.