Skip to content

Commit 5aa204e

Browse files
committed
Merge pull request #2619 from kwood/master
Updated CreateOnlyDefault to call set_context on its default
2 parents 33c4278 + b582d52 commit 5aa204e

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

rest_framework/fields.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ def __init__(self, default):
114114

115115
def set_context(self, serializer_field):
116116
self.is_update = serializer_field.parent.instance is not None
117+
if callable(self.default) and hasattr(self.default, 'set_context'):
118+
self.default.set_context(serializer_field)
117119

118120
def __call__(self):
119121
if self.is_update:

tests/test_fields.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,25 @@ def test_create_only_default_is_not_provided_on_update(self):
317317
'text': 'example',
318318
}
319319

320+
def test_create_only_default_callable_sets_context(self):
321+
"""
322+
CreateOnlyDefault instances with a callable default should set_context
323+
on the callable if possible
324+
"""
325+
class TestCallableDefault:
326+
def set_context(self, serializer_field):
327+
self.field = serializer_field
328+
329+
def __call__(self):
330+
return "success" if hasattr(self, 'field') else "failure"
331+
332+
class TestSerializer(serializers.Serializer):
333+
context_set = serializers.CharField(default=serializers.CreateOnlyDefault(TestCallableDefault()))
334+
335+
serializer = TestSerializer(data={})
336+
assert serializer.is_valid()
337+
assert serializer.validated_data['context_set'] == 'success'
338+
320339

321340
# Tests for field input and output values.
322341
# ----------------------------------------

0 commit comments

Comments
 (0)