File tree 2 files changed +39
-1
lines changed
2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change @@ -274,7 +274,23 @@ def get_attribute(self, instance):
274
274
Given the *outgoing* object instance, return the primitive value
275
275
that should be used for this field.
276
276
"""
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}`.\n The 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 )
278
294
279
295
def get_default (self ):
280
296
"""
Original file line number Diff line number Diff line change
1
+ from __future__ import unicode_literals
1
2
from rest_framework import serializers
2
3
import pytest
3
4
@@ -175,3 +176,24 @@ def test_nested_serialize(self):
175
176
instance = {'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 }
176
177
serializer = self .Serializer (instance )
177
178
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
+ )
You can’t perform that action at this time.
0 commit comments