aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework
diff options
context:
space:
mode:
authorJamie Matthews2012-10-24 11:39:17 +0100
committerJamie Matthews2012-10-24 11:39:17 +0100
commitac2d39892d6b3fbbe5cd53b9ef83367249ba4880 (patch)
tree413fedc79aeedb06722b416fd74af38d767f9c9e /rest_framework
parent388a807f64f60d84556288e2ade4f0fe57a8e66b (diff)
downloaddjango-rest-framework-ac2d39892d6b3fbbe5cd53b9ef83367249ba4880.tar.bz2
Add cross-field validate method
Diffstat (limited to 'rest_framework')
-rw-r--r--rest_framework/serializers.py13
-rw-r--r--rest_framework/tests/serializer.py24
2 files changed, 37 insertions, 0 deletions
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
index 802ca55f..15fe26ee 100644
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -225,6 +225,18 @@ class BaseSerializer(Field):
return data
+ def clean_all(self, attrs):
+ """
+ Run the `validate` method on the serializer, if it exists
+ """
+ try:
+ validate_method = getattr(self, 'validate', None)
+ if validate_method:
+ attrs = validate_method(attrs)
+ except ValidationError as err:
+ self._errors['non_field_errors'] = err.messages
+ return attrs
+
def restore_object(self, attrs, instance=None):
"""
Deserialize a dictionary of attributes into an object instance.
@@ -259,6 +271,7 @@ class BaseSerializer(Field):
if data is not None:
attrs = self.restore_fields(data)
attrs = self.clean_fields(attrs)
+ attrs = self.clean_all(attrs)
else:
self._errors['non_field_errors'] = 'No input provided'
diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py
index a32de80d..936f15aa 100644
--- a/rest_framework/tests/serializer.py
+++ b/rest_framework/tests/serializer.py
@@ -163,6 +163,30 @@ class ValidationTests(TestCase):
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'content': [u'Test not in value']})
+ def test_cross_field_validation(self):
+
+ class CommentSerializerWithCrossFieldValidator(CommentSerializer):
+
+ def validate(self, attrs):
+ if attrs["email"] not in attrs["content"]:
+ raise serializers.ValidationError("Email address not in content")
+ return attrs
+
+ data = {
+ 'email': 'tom@example.com',
+ 'content': 'A comment from tom@example.com',
+ 'created': datetime.datetime(2012, 1, 1)
+ }
+
+ serializer = CommentSerializerWithCrossFieldValidator(data)
+ self.assertTrue(serializer.is_valid())
+
+ data['content'] = 'A comment from foo@bar.com'
+
+ serializer = CommentSerializerWithCrossFieldValidator(data)
+ self.assertFalse(serializer.is_valid())
+ self.assertEquals(serializer.errors, {'non_field_errors': [u'Email address not in content']})
+
class MetadataTests(TestCase):
def test_empty(self):