Skip to content

Commit

Permalink
Merge pull request #2267 from tomchristie/better-misconfigured-serial…
Browse files Browse the repository at this point in the history
…izer-errors

Better errors when serializer has incorrectly named field.
  • Loading branch information
tomchristie committed Dec 13, 2014
2 parents 6158285 + 4fb7571 commit dd712a1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
18 changes: 17 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,23 @@ def get_attribute(self, instance):
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):
"""
Expand Down
22 changes: 22 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import unicode_literals
from rest_framework import serializers
import pytest

Expand Down Expand Up @@ -175,3 +176,24 @@ def test_nested_serialize(self):
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:"
)

0 comments on commit dd712a1

Please sign in to comment.