Отображение продукта, идентификатор которого передан в качестве параметра
Я хочу получить продукт, чей 'id' передан в качестве параметра, как мне это сделать? Например, здесь я передал id равным 1. Обратите внимание, я использую не модель, а словарь
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')
я получаю эту ошибку : индексы списка должны быть целыми числами или фрагментами, а не str
Я предполагаю, что
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')
Я не тестировал его, но считаю, что это лучшее решение вашей проблемы.