I'm trying to display data that I put on a session for my shopping cart project that I'm developing, but here I can't recover the product whose code I passed as a parameter
def index(request):
mes_produits={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
parcou=mes_produits['produits']
contex={'produits':parcou}
return render(request,'shop/index.html',contex)
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
request.session['nom']=selected_product.get('nom')
request.session['prix']=selected_product.get('prix')
contex={'nom':request.session['nom'],'prix':request.session['prix']}
return render(request, 'cart/cart_detail.html',contex)
car_detail.html
{% for key,value in request.session.items %}
Nom : {{value.nom}}
Prix : {{value.prix}}
{% endfor %}
I get a blank page with the name of the keys only
CodePudding user response:
your session object is a dict, not a list of tuple. Try this code in template:
Nom : {{request.session.nom}}
Prix : {{request.session.prix}}
But, you have already set the vars in context, so you can do:
Nom : {{nom}}
Prix : {{prix}}
# And your views.py
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
context={
'nom':selected_product.get('nom'),
'prix':selected_product.get('prix')
}
else:
context = {}
return render(request, 'cart/cart_detail.html',context)
Maybe you do not understand session usage ? https://docs.djangoproject.com/fr/4.1/topics/http/sessions/