From 134f5fa4bc783481d394f9c35d9e9e5880c30103 Mon Sep 17 00:00:00 2001 From: paolopaolopaolo Date: Tue, 22 Sep 2015 11:40:19 -0700 Subject: [PATCH 1/2] Fixes #3265 (now with Test Case) - Added test_data_access_before_save_raises_error test --- tests/test_serializer.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index c18cbb584..e99efe3d2 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -51,6 +51,15 @@ class TestSerializer: 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): From 7640bfea9ed80bd2cb892efebd75a797681f5297 Mon Sep 17 00:00:00 2001 From: paolopaolopaolo Date: Tue, 22 Sep 2015 11:49:51 -0700 Subject: [PATCH 2/2] Add `assert` statement to `.save()` method in Serializer: - Asserts that `_data` does not exist when calling `.save()` --- rest_framework/serializers.py | 6 ++++++ tests/test_serializer.py | 1 + 2 files changed, 7 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 037939e31..a3c26e1ee 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -166,6 +166,12 @@ class BaseSerializer(Field): "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()) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index e99efe3d2..741c6ab17 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -61,6 +61,7 @@ class TestSerializer: with pytest.raises(AssertionError): serializer.save() + class TestValidateMethod: def test_non_field_error_validate_method(self): class ExampleSerializer(serializers.Serializer):