diff options
| -rw-r--r-- | rest_framework/serializers.py | 23 | ||||
| -rw-r--r-- | tests/test_model_serializer.py | 10 |
2 files changed, 17 insertions, 16 deletions
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 143d205d..d417ca80 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -35,7 +35,6 @@ from rest_framework.validators import ( ) import copy import inspect -import sys import warnings # Note: We do the following so that users of the framework can use this style: @@ -658,14 +657,20 @@ class ModelSerializer(Serializer): instance = ModelClass.objects.create(**validated_attrs) except TypeError as exc: msg = ( - 'The mentioned argument might be a field on the serializer ' - 'that is not part of the model. You need to override the ' - 'create() method in your ModelSerializer subclass to support ' - 'this.') - six.reraise( - type(exc), - type(exc)(str(exc) + '. ' + msg), - sys.exc_info()[2]) + 'Got a `TypeError` when calling `%s.objects.create()`. ' + 'This may be because you have a writable field on the ' + 'serializer class that is not a valid argument to ' + '`%s.objects.create()`. You may need to make the field ' + 'read-only, or override the %s.create() method to handle ' + 'this correctly.\nOriginal exception text was: %s.' % + ( + ModelClass.__name__, + ModelClass.__name__, + self.__class__.__name__, + exc + ) + ) + raise TypeError(msg) # Save many-to-many relationships after the instance is created. if many_to_many: diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 90767dac..1bcd58e0 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -10,7 +10,6 @@ from django.core.validators import MaxValueValidator, MinValueValidator, MinLeng from django.db import models from django.test import TestCase from rest_framework import serializers -import pytest def dedent(blocktext): @@ -87,13 +86,10 @@ class TestModelSerializer(TestCase): 'non_model_field': 'bar', }) serializer.is_valid() - with pytest.raises(TypeError): + with self.assertRaises(TypeError) as excinfo: serializer.save() - - try: - serializer.save() - except TypeError as exc: - assert 'ModelSerializer' in str(exc) + msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.' + assert str(excinfo.exception).startswith(msginitial) class TestRegularFieldMappings(TestCase): |
