From 05cbec9dd7f9f0b6a9b59b29ac6c9272b6ae50d8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 17 Oct 2014 13:23:14 +0100 Subject: Use serializers.ValidationError --- docs/topics/3.0-announcement.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'docs') diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index f868b344..658b50d3 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -144,11 +144,15 @@ The corresponding code would now look like this: logging.info('Creating ticket "%s"' % name) 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_`. @@ -156,14 +160,14 @@ The `validate_` method hooks that can be attached to serializer clas def validate_score(self, attrs, source): 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 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): 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 Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. -- cgit v1.2.3