From 6ccbdd10ad91bbc2116c6adf520096e9da95b8e0 Mon Sep 17 00:00:00 2001 From: Marko Tibold Date: Tue, 30 Oct 2012 00:03:24 +0100 Subject: [PATCH 1/2] Adding failing tests that show null=True model fields are won't validate if their value is omitted. --- rest_framework/tests/models.py | 5 +++++ rest_framework/tests/serializer.py | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py index ac73a4bbb..fb23e359f 100644 --- a/rest_framework/tests/models.py +++ b/rest_framework/tests/models.py @@ -116,3 +116,8 @@ class BlogPost(RESTFrameworkModel): class BlogPostComment(RESTFrameworkModel): text = models.TextField() blog_post = models.ForeignKey(BlogPost) + + +class Person(RESTFrameworkModel): + name = models.CharField(max_length=10) + age = models.IntegerField(null=True, blank=True) diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index 5df3bd7e0..eb21dc461 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -43,6 +43,11 @@ class ActionItemSerializer(serializers.ModelSerializer): model = ActionItem +class PersonSerializer(serializers.ModelSerializer): + class Meta: + model = Person + + class BasicTests(TestCase): def setUp(self): self.comment = Comment( @@ -188,6 +193,14 @@ class ValidationTests(TestCase): self.assertFalse(serializer.is_valid()) self.assertEquals(serializer.errors, {'non_field_errors': [u'Email address not in content']}) + def test_null_is_true_fields(self): + """ + Omitting a value for null-field should validate. + """ + serializer = PersonSerializer({'name': 'marko'}) + self.assertEquals(serializer.is_valid(), True) + self.assertEquals(serializer.errors, {}) + class MetadataTests(TestCase): def test_empty(self): From 206859529780adbe7f49ee1e4d466e3b4fe13099 Mon Sep 17 00:00:00 2001 From: Marko Tibold Date: Tue, 30 Oct 2012 00:09:40 +0100 Subject: [PATCH 2/2] Set a ModelSerializer field to required=False if the ModelField has null=True set. --- rest_framework/serializers.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index ce04b3e20..e705bf772 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -393,6 +393,9 @@ class ModelSerializer(Serializer): Creates a default instance of a basic non-relational field. """ kwargs = {} + if model_field.null: + kwargs['required'] = False + if model_field.has_default(): kwargs['required'] = False kwargs['default'] = model_field.get_default()