Display a product whose ID is passed as a parameter

Question:

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

Asked By: Khalifa

||

Answers:

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.

Answered By: actuallyatiger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.