Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why Django showing object has no attribute?

Hope you are doing well, i am beginner to the django and python, encountered the error while practicing which is on REST API FRAMEWORK of DictField . i took an example on DictField. I have posted a code below please have a look. feel free to ask if you have any questions. please solve the issue. Thanks a lot for your help.

app1/serializers.py

from rest_framework import serializers

class Geeks(object):
    def __init__(self, dictionary):
        self.dict = dictionary


class GeeksSerializer(serializers.Serializer):
    dictionary = serializers.DictField()
    child = serializers.CharField()

python manage.py shell


>>> demo = {}
>>> demo['name'] = "Naveen"
>>> demo['age'] = 21
>>> obj = Geeks(demo)
>>> serializer = GeeksSerializer(obj)
>>> serializer.data
Error:
Traceback (most recent call last):
 File "rest_framework\fields.py", line 457, in get_attribute
  return get_attribute(instance, self.source_attrs)
 File "rest_framework\fields.py", line 97, in get_attribute
  instance = getattr(instance, attr)
AttributeError: 'Geeks' object has no attribute 'dictionary'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "rest_framework\serializers.py", line 555, in data
   ret = super().data
 File "rest_framework\serializers.py", line 253, in data
   self._data = self.to_representation(self.instance)
 File "rest_framework\serializers.py", line 509, in to_representation
   attribute = field.get_attribute(instance)
 File "rest_framework\fields.py", line 490, in get_attribute
raise type(exc)(msg)

AttributeError: Got AttributeError when attempting to get a value for field `dictionary` on serializer `GeeksSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Geeks` instance.
Original exception text was: 'Geeks' object has no attribute 'dictionary'.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your Geeks object has a dict attribute, not a dictionary attribute, so

‘Geeks’ object has no attribute ‘dictionary’.

makes total sense.

If you want the dictionary serializer field to read from dict, set the source attribute on the field.

dictionary = serializers.DictField(source="dict")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading