Skip to content

Commit 76ac641

Browse files
committed
Minor tweaks for helpful message on Model.objects.create() failure.
1 parent 54b7b32 commit 76ac641

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

rest_framework/serializers.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
)
3636
import copy
3737
import inspect
38-
import sys
3938
import warnings
4039

4140
# Note: We do the following so that users of the framework can use this style:
@@ -658,14 +657,20 @@ def create(self, validated_attrs):
658657
instance = ModelClass.objects.create(**validated_attrs)
659658
except TypeError as exc:
660659
msg = (
661-
'The mentioned argument might be a field on the serializer '
662-
'that is not part of the model. You need to override the '
663-
'create() method in your ModelSerializer subclass to support '
664-
'this.')
665-
six.reraise(
666-
type(exc),
667-
type(exc)(str(exc) + '. ' + msg),
668-
sys.exc_info()[2])
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.\nOriginal exception text was: %s.' %
666+
(
667+
ModelClass.__name__,
668+
ModelClass.__name__,
669+
self.__class__.__name__,
670+
exc
671+
)
672+
)
673+
raise TypeError(msg)
669674

670675
# Save many-to-many relationships after the instance is created.
671676
if many_to_many:

tests/test_model_serializer.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from django.db import models
1111
from django.test import TestCase
1212
from rest_framework import serializers
13-
import pytest
1413

1514

1615
def dedent(blocktext):
@@ -87,13 +86,10 @@ class Meta:
8786
'non_model_field': 'bar',
8887
})
8988
serializer.is_valid()
90-
with pytest.raises(TypeError):
89+
with self.assertRaises(TypeError) as excinfo:
9190
serializer.save()
92-
93-
try:
94-
serializer.save()
95-
except TypeError as exc:
96-
assert 'ModelSerializer' in str(exc)
91+
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
92+
assert str(excinfo.exception).startswith(msginitial)
9793

9894

9995
class TestRegularFieldMappings(TestCase):

0 commit comments

Comments
 (0)