aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTom Christie2014-12-02 13:04:49 +0000
committerTom Christie2014-12-02 13:04:49 +0000
commit76ac641fbd6c9d7dff5da3c551c3fd1ef7dedd2e (patch)
tree9cc8e92aa9683be5ff7f61d043756cd7b1f26515
parent54b7b32818fc9b8872b65d25d5684c72b8e60ae0 (diff)
downloaddjango-rest-framework-76ac641fbd6c9d7dff5da3c551c3fd1ef7dedd2e.tar.bz2
Minor tweaks for helpful message on Model.objects.create() failure.
-rw-r--r--rest_framework/serializers.py23
-rw-r--r--tests/test_model_serializer.py10
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):