Issue
This Content is from Stack Overflow. Question asked by Khalifa
I retrieved a list of products via an API, then I use django-shopping-cart to generate my cart
But I have an error ‘dict’ object has no attribute ‘code’.
the error is at this line : if product.code == code ,while there is indeed the code attribute in the dict
def cart_add(request,code):
url='http://myapi/Product/GetProducts'
x=requests.get(url)
content=x.json()
all_products=content['products']
for product in all_products :
if product.code == code :
cart=Cart(request)
cart.add(product = product.code)
return render(request,'shop/deatil.html')
At the API level, the dictionary specification is of the form:
dict = {
"products": [
{
"code": "4mlk2",
"designation": "kaka"
},
{
"code": "455ml",
"designation": "koko"
},
....
]
}
Solution
Classic issue I’m also having when switching over eg from Javascript 🙂
There is no dot notation in python to access dicts. There are basically 2 way to access a dict in python:
product["code"]
or
product.get("code")
The latter has the advantage that you can pass in a default value in case the key "code" is not available:
product.get("code", "123421")
This Question was asked in StackOverflow by Khalifa and Answered by mightym It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.