From 78e8b1b0108bb8338aa578ea2f4a0237d4edd1d4 Mon Sep 17 00:00:00 2001 From: Kevin Wood Date: Fri, 27 Feb 2015 22:14:15 -0800 Subject: [PATCH 1/2] Updated CreateOnlyDefault to call set_context on its default (if callable) --- rest_framework/fields.py | 2 ++ tests/test_fields.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 13301f31b..c327f11bc 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -114,6 +114,8 @@ class CreateOnlyDefault: def set_context(self, serializer_field): self.is_update = serializer_field.parent.instance is not None + if callable(self.default) and hasattr(self.default, 'set_context'): + self.default.set_context(serializer_field) def __call__(self): if self.is_update: diff --git a/tests/test_fields.py b/tests/test_fields.py index 7f5f81029..2ffffd55a 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -317,6 +317,22 @@ class TestCreateOnlyDefault: 'text': 'example', } + def test_create_only_default_callable_sets_context(self): + """ CreateOnlyDefault instances with a callable default should set_context on the callable if possible """ + class TestCallableDefault: + def set_context(self, serializer_field): + self.field = serializer_field + + def __call__(self): + return "success" if hasattr(self, 'field') else "failure" + + class TestSerializer(serializers.Serializer): + context_set = serializers.CharField(default=serializers.CreateOnlyDefault(TestCallableDefault())) + + serializer = TestSerializer(data={}) + assert serializer.is_valid() + assert serializer.validated_data['context_set'] == 'success' + # Tests for field input and output values. # ---------------------------------------- From b582d52afbad81c56edad8ea3b6d2ac2d352b87e Mon Sep 17 00:00:00 2001 From: Kevin Wood Date: Sat, 28 Feb 2015 13:06:47 -0800 Subject: [PATCH 2/2] Fix docstring formatting --- tests/test_fields.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_fields.py b/tests/test_fields.py index 2ffffd55a..1aa528da6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -318,7 +318,10 @@ class TestCreateOnlyDefault: } def test_create_only_default_callable_sets_context(self): - """ CreateOnlyDefault instances with a callable default should set_context on the callable if possible """ + """ + CreateOnlyDefault instances with a callable default should set_context + on the callable if possible + """ class TestCallableDefault: def set_context(self, serializer_field): self.field = serializer_field