From c8416df0c4b7179eeaf86b61c32907f32494b85c Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Mon, 18 Mar 2013 14:27:15 +1300 Subject: [PATCH 1/3] accept all WritableField kwargs for writable serializers (eg required=True) --- rest_framework/serializers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 21336dc29..c6599886c 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -129,8 +129,8 @@ class BaseSerializer(WritableField): _dict_class = SortedDictWithMetadata def __init__(self, instance=None, data=None, files=None, - context=None, partial=False, many=None, source=None): - super(BaseSerializer, self).__init__(source=source) + context=None, partial=False, many=None, **kwargs): + super(BaseSerializer, self).__init__(**kwargs) self.opts = self._options_class(self.Meta) self.parent = None self.root = None From d6d5b1d82a4ccc1a2fe29ff18e9ecf7c196a07a5 Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Mon, 18 Mar 2013 14:50:08 +1300 Subject: [PATCH 2/3] allow default values in writable serializer fields --- rest_framework/serializers.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c6599886c..cc6d60da1 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -360,7 +360,9 @@ class BaseSerializer(WritableField): except KeyError: if self.required: raise ValidationError(self.error_messages['required']) - return + if self.default is None: + return + value = copy.deepcopy(self.default) # Set the serializer object if it exists obj = getattr(self.parent.object, field_name) if self.parent.object else None From 101fa26ebc092a43acbf3f28617eb58be7629b5f Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Mon, 18 Mar 2013 16:05:34 +1300 Subject: [PATCH 3/3] use writablefield style for serializer handling of self.default --- rest_framework/serializers.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index cc6d60da1..a81cbc291 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -358,11 +358,13 @@ class BaseSerializer(WritableField): try: value = data[field_name] except KeyError: - if self.required: - raise ValidationError(self.error_messages['required']) - if self.default is None: + if self.default is not None and not self.partial: + # Note: partial updates shouldn't set defaults + value = copy.deepcopy(self.default) + else: + if self.required: + raise ValidationError(self.error_messages['required']) return - value = copy.deepcopy(self.default) # Set the serializer object if it exists obj = getattr(self.parent.object, field_name) if self.parent.object else None