Issue
This Content is from Stack Overflow. Question asked by Khalifa
I would like to retrieve the product whose ‘id’ is passed as a parameter, how do I do this?
For example here I passed the id equal to 1
Note I don’t use a model but a dictionary
def cart_add(request, id):
dico={"produits":[{'id':1,'name':'pomme de terre','price':1250}]}
mes_produits=dico['produits']
cart = Cart(request)
mes_produits['id']=id
product=mes_produits['id']
cart.add(product=product)
return render(request, 'cart/cart_detail.html')
i get this error : list indices must be integers or slices, not str
Solution
I’m assuming that
def cart_add(request, id):
dico={"produits":[{'id':1,'name':'pomme de terre','price':1250}]}
mes_produits=dico['produits']
cart = Cart(request)
# sets the product to the first product found with the correct ID
# (in case there are duplicates), if none are found set product to None.
selected_product = next((item for item in mes_produits if item["id"] == id), None)
if selected_product != None:
cart.add(product=selected_product) # passes [id,name,price] to cart.add()
else:
print("item not found")
return render(request, 'cart/cart_detail.html')
I haven’t tested it but I believe it’s the best solution to your problem.
This Question was asked in StackOverflow by Khalifa and Answered by actuallyatiger It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.