mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-29 13:04:03 +03:00
Updated CreateOnlyDefault to call set_context on its default (if callable)
This commit is contained in:
parent
33c4278ec8
commit
78e8b1b010
|
@ -114,6 +114,8 @@ class CreateOnlyDefault:
|
||||||
|
|
||||||
def set_context(self, serializer_field):
|
def set_context(self, serializer_field):
|
||||||
self.is_update = serializer_field.parent.instance is not None
|
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):
|
def __call__(self):
|
||||||
if self.is_update:
|
if self.is_update:
|
||||||
|
|
|
@ -317,6 +317,22 @@ class TestCreateOnlyDefault:
|
||||||
'text': 'example',
|
'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.
|
# Tests for field input and output values.
|
||||||
# ----------------------------------------
|
# ----------------------------------------
|
||||||
|
|
Loading…
Reference in New Issue
Block a user