From a3a06d11cc39da55d34f99e272bf092a2dcd4c5c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 28 Jan 2013 12:56:42 +0000 Subject: Ensure model field validation is performed for ModelSerializers with a custom restore_object method. Fixes #623. --- rest_framework/serializers.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) (limited to 'rest_framework/serializers.py') diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 6ecc7b45..0fed2c29 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -513,6 +513,22 @@ class ModelSerializer(Serializer): exclusions.remove(field_name) return exclusions + def full_clean(self, instance): + """ + Perform Django's full_clean, and populate the `errors` dictionary + if any validation errors occur. + + Note that we don't perform this inside the `.restore_object()` method, + so that subclasses can override `.restore_object()`, and still get + the full_clean validation checking. + """ + try: + instance.full_clean(exclude=self.get_validation_exclusions()) + except ValidationError, err: + self._errors = err.message_dict + return None + return instance + def restore_object(self, attrs, instance=None): """ Restore the model instance. @@ -544,14 +560,16 @@ class ModelSerializer(Serializer): else: instance = self.opts.model(**attrs) - try: - instance.full_clean(exclude=self.get_validation_exclusions()) - except ValidationError, err: - self._errors = err.message_dict - return None - return instance + def from_native(self, data, files): + """ + Override the default method to also include model field validation. + """ + instance = super(ModelSerializer, self).from_native(data, files) + if instance: + return self.full_clean(instance) + def save(self): """ Save the deserialized object and return it. -- cgit v1.2.3