I have been having trouble understanding why the object (obj) passed into field_to_native() changes from Nonetype to a correct object once I change the attribute...
Here's the original issue: Splitting model instance for serializer into 3 different fields
mariodev from stackoverflow helped me on the original issue, but a strange bug both of us cannot figure out:
Here's the code where it seems to have the problem:
COORD = dict(x=0, y=1, z=2)
class CoordField(serializers.Field):
def field_to_native(self, obj, field_name):
#retrieve and split coords
coor = obj.xyz.split('x')
return int(coor[COORD[field_name]])
class NoteSerializer(serializers.ModelSerializer):
owner = serializers.Field(source='owner.username')
firstname = serializers.Field(source='owner.first_name')
lastname = serializers.Field(source='owner.last_name')
x = CoordField()
y = CoordField()
z = CoordField()
class Meta:
model = Note
fields = ('id','owner','firstname','lastname','text','color','time','x', 'y', 'z')
xyz is a instance in the model Note. According to the traceback, when I do obj.xyz, the obj = None.
Weirdly, if I do obj.color, the obj returns correctly (Note: someuser)
I don't understand how the obj can change just by changing the attribute.
What's beyond me is that the JSON data 'x' 'y' and 'z' ARE being passed to the view, and my div boxes get the correct left, top, and z-index CSS data. If this works, why am I getting an error?
If there's an error, why is the data still getting through?
style="left: 343px; top: 110px; z-index: 3;"
As you can see, the x,y,z DID pass through.
Any enlightenment would be wonderful! Thanks a bunch!
Here's the traceback in text view:
Traceback:
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
140. response = response.render()
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/django/template/response.py" in render
105. self.content = self.rendered_content
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/response.py" in rendered_content
59. ret = renderer.render(self.data, media_type, context)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/renderers.py" in render
582. post_form = self.get_rendered_html_form(view, 'POST', request)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/renderers.py" in get_rendered_html_form
485. data = serializer.data
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/serializers.py" in data
510. self._data = self.to_native(obj)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/serializers.py" in to_native
309. value = field.field_to_native(obj, field_name)
File "/home1/thecupno/django/notes/desk/serializers.py" in field_to_native
10. coor = obj.xyz#.split('x') <-- I commented out .split, and the problem still persists.
Exception Type: AttributeError at /desk/restnote/
Exception Value: 'NoneType' object has no attribute 'xyz'