'Dict' Object Has No Attribute 'Id'

This is my code. I'm trying to translate xml string into python list to be shown in html template.

self.task_xml = "<?xml version="1.0" encoding="utf-8"?>
    <django-objects version="1.0">
<object model="task.task" pk="31">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">0</field>
</object>
<object model="task.task" pk="32">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">0</field>
</object>
<object model="task.task" pk="33">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">31</field>
</object>
<object model="task.task" pk="34">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">31</field>
</object>
</django-objects>"

 58         self.xmlData = ET.fromstring(self.db.task_xml)
 59 
 60         self.task_list = []
 61         taskList = []                                                           
 62         for obj in self.xmlData.iter("object"):
 63             parent_task_id = obj.find("field[@name='parent_task_id']").text
 64             if parent_task_id == EMPTY_UUID:
 65                 taskList.append({'id': obj.get("pk"),
 66                     'name': obj.find("field[@name='name']").text,
 67                     'parent_task_id': parent_task_id ,
 68                     })
 69         # Apprend taskList:
 70         for task in taskList:
 71             taskViewModel = TaskViewModel(task.id, True)
 72             self.task_list.append(taskViewModel)

But I'm getting the error:

'dict' object has no attribute 'id'

And it is task.id in line 71

Do you think I have a problem with this in line 65:

'id': obj.get("pk")
1

2 Answers

You are accessing the dictionary wrongly. You need to use subscript with string 'id' , Example -

taskViewModel = TaskViewModel(task['id'], True)
2

I got the same error when accessing "id" in dictionary with dot "." like JavaScript as shown below because I also use JavaScript quite often in addition to Python:

user = {"id": 1, "name": "John"}
print(user.id) # Error

So, I accessed "id" with brackets "[]" as shown below then the error was solved:

user = {"id": 1, "name": "John"}
print(user["id"]) # 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest