Home > Software engineering >  Display a product whose ID is passed as a parameter
Display a product whose ID is passed as a parameter

Time:09-19

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

CodePudding user response:

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.

  • Related