From 51fae73f3d565e2702c72ff9841cc072d6490804 Mon Sep 17 00:00:00 2001 From: Jamie Matthews Date: Wed, 24 Oct 2012 09:28:10 +0100 Subject: Implement per-field validation on Serializers --- docs/api-guide/serializers.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'docs') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index c10a3f44..e1e12e74 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -78,6 +78,23 @@ When deserializing data, you always need to call `is_valid()` before attempting **TODO: Describe validation in more depth** +## Custom field validation + +Like Django forms, you can specify custom field-level validation by adding `clean_()` methods to your `Serializer` subclass. This method takes a dictionary of deserialized data as a first argument, and the field name in that data as a second argument (which will be either the name of the field or the value of the `source` argument, if one was provided.) It should either return the data dictionary or raise a `ValidationError`. For example: + + class BlogPostSerializer(Serializer): + title = serializers.CharField(max_length=100) + content = serializers.CharField() + + def clean_title(self, data, source): + """ + Check that the blog post is about Django + """ + value = data[source] + if "Django" not in value: + raise ValidationError("Blog post is not about Django") + return data + ## Dealing with nested objects The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, -- cgit v1.2.3