File tree Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -653,7 +653,24 @@ def create(self, validated_attrs):
653
653
if relation_info .to_many and (field_name in validated_attrs ):
654
654
many_to_many [field_name ] = validated_attrs .pop (field_name )
655
655
656
- instance = ModelClass .objects .create (** validated_attrs )
656
+ try :
657
+ instance = ModelClass .objects .create (** validated_attrs )
658
+ except TypeError as exc :
659
+ msg = (
660
+ 'Got a `TypeError` when calling `%s.objects.create()`. '
661
+ 'This may be because you have a writable field on the '
662
+ 'serializer class that is not a valid argument to '
663
+ '`%s.objects.create()`. You may need to make the field '
664
+ 'read-only, or override the %s.create() method to handle '
665
+ 'this correctly.\n Original exception text was: %s.' %
666
+ (
667
+ ModelClass .__name__ ,
668
+ ModelClass .__name__ ,
669
+ self .__class__ .__name__ ,
670
+ exc
671
+ )
672
+ )
673
+ raise TypeError (msg )
657
674
658
675
# Save many-to-many relationships after the instance is created.
659
676
if many_to_many :
Original file line number Diff line number Diff line change @@ -26,6 +26,10 @@ class CustomField(models.Field):
26
26
pass
27
27
28
28
29
+ class OneFieldModel (models .Model ):
30
+ char_field = models .CharField (max_length = 100 )
31
+
32
+
29
33
class RegularFieldsModel (models .Model ):
30
34
"""
31
35
A model class for testing regular flat fields.
@@ -68,6 +72,26 @@ class FieldOptionsModel(models.Model):
68
72
choices_field = models .CharField (max_length = 100 , choices = COLOR_CHOICES )
69
73
70
74
75
+ class TestModelSerializer (TestCase ):
76
+ def test_create_method (self ):
77
+ class TestSerializer (serializers .ModelSerializer ):
78
+ non_model_field = serializers .CharField ()
79
+
80
+ class Meta :
81
+ model = OneFieldModel
82
+ fields = ('char_field' , 'non_model_field' )
83
+
84
+ serializer = TestSerializer (data = {
85
+ 'char_field' : 'foo' ,
86
+ 'non_model_field' : 'bar' ,
87
+ })
88
+ serializer .is_valid ()
89
+ with self .assertRaises (TypeError ) as excinfo :
90
+ serializer .save ()
91
+ msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
92
+ assert str (excinfo .exception ).startswith (msginitial )
93
+
94
+
71
95
class TestRegularFieldMappings (TestCase ):
72
96
def test_regular_fields (self ):
73
97
"""
You can’t perform that action at this time.
0 commit comments