Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display a product whose ID is passed as a parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading