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"
},
....
]
}
CodePudding user response:
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")