Answer the question
In order to leave comments, you need to log in
How to display dictionary values from a list of Python/Django session objects?
I need to add and withdraw objects from the session in such a way that I can then display the characteristics of the displayed objects!
There is a session with a list that has dictionaries -
cart(переменная сессии) [{'price': 436, 'product_id': 5}, {'price': 436, 'product_id': 6}]
def add_product_to_cart(request):
if request.method == 'POST':
id = int(request.POST['product_id'])
price = int(request.POST['price'])
if 'cart' not in request.session:
request.session['cart'] = []
request.session['cart'].append(dict({'product_id': id, 'price': price}))
request.session.modified = True
return redirect("/")
def show_cart(request):
cart = request.session.get('cart')
product_items = Product.objects.filter(id__in=cart) #пробовал и так Product.objects.filter(id__in=request.session['cart'])
content={
"product_items":product_items
}
return render (request, "orderdetail.html", content)
def add_product_to_cart(request, id):
if 'cart' not in request.session:
request.session['cart'] = []
request.session['cart'].append(int(id))
request.session.modified = True
return redirect("/")
def show_cart(request):
cart = request.session.get('cart')
product_items = Product.objects.filter(id__in=cart)
content={
"product_items":product_items
}
return render (request, "orderdetail.html", content)
Answer the question
In order to leave comments, you need to log in
My answer is:
views.py
def add_product_to_cart(request):
if request.method == 'POST':
id = int(request.POST['product_id'])
if 'cart' not in request.session:
request.session['cart'] = []
request.session['cart'].append(int(id))
request.session.modified = True
return redirect("/")
def show_cart(request):
cart = request.session.get('cart')
product_items = Product.objects.filter(id__in=cart) #можно и так Product.objects.filter(id__in=request.session['cart'])
content={
"product_items":product_items
}
return render (request, "orderdetail.html", content)
def add_product_to_cart(request):
if request.method == 'POST':
id = int(request.POST['product_id'])
price = int(request.POST['price'])
if 'cart' not in request.session:
request.session['cart'] = []
request.session['cart'].append(dict({'product_id': id, 'price': price}))
request.session.modified = True
return redirect("/")
def show_cart(request):
cart = request.session.get('cart')
product_items = Product.objects.filter(id__in=(x['product_id'] for x in cart) )#можно прописать и для price вот только фактически это не нужно...
content={
"product_items":product_items
}
return render (request, "orderdetail.html", content)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question