Skip to content

Commit

Permalink
Updated CreateOnlyDefault to call set_context on its default (if call…
Browse files Browse the repository at this point in the history
…able)
  • Loading branch information
Kevin Wood committed Feb 28, 2015
1 parent 33c4278 commit 78e8b1b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ def __init__(self, default):

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:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,22 @@ def test_create_only_default_is_not_provided_on_update(self):
'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.
# ----------------------------------------
Expand Down

0 comments on commit 78e8b1b

Please sign in to comment.