Skip to content

Commit dd712a1

Browse files
committed
Merge pull request #2267 from tomchristie/better-misconfigured-serializer-errors
Better errors when serializer has incorrectly named field.
2 parents 6158285 + 4fb7571 commit dd712a1

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

rest_framework/fields.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,23 @@ def get_attribute(self, instance):
274274
Given the *outgoing* object instance, return the primitive value
275275
that should be used for this field.
276276
"""
277-
return get_attribute(instance, self.source_attrs)
277+
try:
278+
return get_attribute(instance, self.source_attrs)
279+
except (KeyError, AttributeError) as exc:
280+
msg = (
281+
'Got {exc_type} when attempting to get a value for field '
282+
'`{field}` on serializer `{serializer}`.\nThe serializer '
283+
'field might be named incorrectly and not match '
284+
'any attribute or key on the `{instance}` instance.\n'
285+
'Original exception text was: {exc}.'.format(
286+
exc_type=type(exc).__name__,
287+
field=self.field_name,
288+
serializer=self.parent.__class__.__name__,
289+
instance=instance.__class__.__name__,
290+
exc=exc
291+
)
292+
)
293+
raise type(exc)(msg)
278294

279295
def get_default(self):
280296
"""

tests/test_serializer.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import unicode_literals
12
from rest_framework import serializers
23
import pytest
34

@@ -175,3 +176,24 @@ def test_nested_serialize(self):
175176
instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
176177
serializer = self.Serializer(instance)
177178
assert serializer.data == self.data
179+
180+
181+
class TestIncorrectlyConfigured:
182+
def test_incorrect_field_name(self):
183+
class ExampleSerializer(serializers.Serializer):
184+
incorrect_name = serializers.IntegerField()
185+
186+
class ExampleObject:
187+
def __init__(self):
188+
self.correct_name = 123
189+
190+
instance = ExampleObject()
191+
serializer = ExampleSerializer(instance)
192+
with pytest.raises(AttributeError) as exc_info:
193+
serializer.data
194+
msg = str(exc_info.value)
195+
assert msg.startswith(
196+
"Got AttributeError when attempting to get a value for field `incorrect_name` on serializer `ExampleSerializer`.\n"
197+
"The serializer field might be named incorrectly and not match any attribute or key on the `ExampleObject` instance.\n"
198+
"Original exception text was:"
199+
)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy