N
N
nazandr2016-03-19 21:30:19
Django
nazandr, 2016-03-19 21:30:19

How to add list from id to Django session?

I'm writing a shopping cart for an online store, I want to save a list of products in the session, but the next time I access 'items', I can't get the list. It looks like it's empty

def add(request, prod_id):
    if prod_id in request.session['items']:
    	return redirect('/product/%s' % prod_id)
    else:
    	items = request.session['items'] = []
    	items.append(prod_id)
    	return redirect('/product/%s' % prod_id)

def show(request):
  items = request.session['items']
  return render_to_response('show_cart.html', {'prod': Product.objects.all(), 'cart_items': items })

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-03-19
@nazandr

def add(request, prod_id):
    if 'items' not in request.session:
        request.session['items'] = []
    if prod_id not in request.session['items']:
    	request.session['items'].append(prod_id)
        request.session.modified = True
    return redirect('/product/%s' % prod_id)

upd:
Checked. Everything works with .save() and c modified = True.

S
sim3x, 2016-03-19
@sim3x

https://docs.djangoproject.com/en/1.9/topics/http/...
similar to
https://docs.djangoproject.com/en/1.9/topics/http/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question