Conflicts:
	rest_framework/serializers.py
This commit is contained in:
Ben Oswald 2014-12-13 18:44:59 +01:00
commit c434d1b72f
3 changed files with 41 additions and 1 deletions

View File

@ -274,7 +274,23 @@ class Field(object):
Given the *outgoing* object instance, return the primitive value
that should be used for this field.
"""
return get_attribute(instance, self.source_attrs)
try:
return get_attribute(instance, self.source_attrs)
except (KeyError, AttributeError) as exc:
msg = (
'Got {exc_type} when attempting to get a value for field '
'`{field}` on serializer `{serializer}`.\nThe serializer '
'field might be named incorrectly and not match '
'any attribute or key on the `{instance}` instance.\n'
'Original exception text was: {exc}.'.format(
exc_type=type(exc).__name__,
field=self.field_name,
serializer=self.parent.__class__.__name__,
instance=instance.__class__.__name__,
exc=exc
)
)
raise type(exc)(msg)
def get_default(self):
"""

View File

@ -611,6 +611,7 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
# profile = ProfileSerializer()
assert not any(
isinstance(field, BaseSerializer) and (key in validated_data)
and isinstance(validated_data[key], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable nested'
@ -630,6 +631,7 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
# address = serializer.CharField('profile.address')
assert not any(
'.' in field.source and (key in validated_data) and (field.read_only is not True)
and isinstance(validated_data[key], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable dotted-source '

View File

@ -1,3 +1,4 @@
from __future__ import unicode_literals
from rest_framework import serializers
import pytest
@ -175,3 +176,24 @@ class TestStarredSource:
instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
serializer = self.Serializer(instance)
assert serializer.data == self.data
class TestIncorrectlyConfigured:
def test_incorrect_field_name(self):
class ExampleSerializer(serializers.Serializer):
incorrect_name = serializers.IntegerField()
class ExampleObject:
def __init__(self):
self.correct_name = 123
instance = ExampleObject()
serializer = ExampleSerializer(instance)
with pytest.raises(AttributeError) as exc_info:
serializer.data
msg = str(exc_info.value)
assert msg.startswith(
"Got AttributeError when attempting to get a value for field `incorrect_name` on serializer `ExampleSerializer`.\n"
"The serializer field might be named incorrectly and not match any attribute or key on the `ExampleObject` instance.\n"
"Original exception text was:"
)