Minor tweaks for helpful message on Model.objects.create() failure.

This commit is contained in:
Tom Christie 2014-12-02 13:04:49 +00:00
parent 54b7b32818
commit 76ac641fbd
2 changed files with 17 additions and 16 deletions

View File

@ -35,7 +35,6 @@ from rest_framework.validators import (
) )
import copy import copy
import inspect import inspect
import sys
import warnings import warnings
# Note: We do the following so that users of the framework can use this style: # 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) instance = ModelClass.objects.create(**validated_attrs)
except TypeError as exc: except TypeError as exc:
msg = ( msg = (
'The mentioned argument might be a field on the serializer ' 'Got a `TypeError` when calling `%s.objects.create()`. '
'that is not part of the model. You need to override the ' 'This may be because you have a writable field on the '
'create() method in your ModelSerializer subclass to support ' 'serializer class that is not a valid argument to '
'this.') '`%s.objects.create()`. You may need to make the field '
six.reraise( 'read-only, or override the %s.create() method to handle '
type(exc), 'this correctly.\nOriginal exception text was: %s.' %
type(exc)(str(exc) + '. ' + msg), (
sys.exc_info()[2]) ModelClass.__name__,
ModelClass.__name__,
self.__class__.__name__,
exc
)
)
raise TypeError(msg)
# Save many-to-many relationships after the instance is created. # Save many-to-many relationships after the instance is created.
if many_to_many: if many_to_many:

View File

@ -10,7 +10,6 @@ from django.core.validators import MaxValueValidator, MinValueValidator, MinLeng
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
from rest_framework import serializers from rest_framework import serializers
import pytest
def dedent(blocktext): def dedent(blocktext):
@ -87,13 +86,10 @@ class TestModelSerializer(TestCase):
'non_model_field': 'bar', 'non_model_field': 'bar',
}) })
serializer.is_valid() serializer.is_valid()
with pytest.raises(TypeError): with self.assertRaises(TypeError) as excinfo:
serializer.save() serializer.save()
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
try: assert str(excinfo.exception).startswith(msginitial)
serializer.save()
except TypeError as exc:
assert 'ModelSerializer' in str(exc)
class TestRegularFieldMappings(TestCase): class TestRegularFieldMappings(TestCase):