Skip to content

Commit

Permalink
Merge pull request #3431 from paolopaolopaolo/issue-3265
Browse files Browse the repository at this point in the history
Guard against calling `serializer.data` before `serializer.save()`
  • Loading branch information
tomchristie committed Sep 23, 2015
2 parents 7661398 + 7640bfe commit 5144316
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,12 @@ def save(self, **kwargs):
"For example: 'serializer.save(owner=request.user)'.'"
)

assert not hasattr(self, '_data'), (
"You cannot call `.save()` after accessing `serializer.data`."
"If you need to access data before committing to the database then "
"inspect 'serializer.validated_data' instead. "
)

validated_data = dict(
list(self.validated_data.items()) +
list(kwargs.items())
Expand Down
10 changes: 10 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ class MissingAttributes:
with pytest.raises(AttributeError):
serializer.data

def test_data_access_before_save_raises_error(self):
def create(validated_data):
return validated_data
serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
serializer.create = create
assert serializer.is_valid()
assert serializer.data == {'char': 'abc', 'integer': 123}
with pytest.raises(AssertionError):
serializer.save()


class TestValidateMethod:
def test_non_field_error_validate_method(self):
Expand Down

0 comments on commit 5144316

Please sign in to comment.