Chidananda Nayak
Chidananda Nayak

Reputation: 1201

how to remove an item from django session?

I do have two items in request.session.get('product_key'). I am trying to delete one product.

m =  request.session['product_key']
m.remove('768')

when i am trying to delete one product from the session its getting deleted from the variable but not from actual session. when i am printing m its giving me single product while i am typing request.session.get('product_key') its giving me two products.

So, how can i achieve so?

Edit:

I dont want to delete complete session, i want to delete one variable from the session,i have 2 items in one key name. print(request.session['product_key']) = ['123','768']

Upvotes: 0

Views: 4047

Answers (3)

Irfan wani
Irfan wani

Reputation: 5075

Here you go;

request.session["your key"].pop(index of the element you want to remove)
request.session.modified = True

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599540

If you modify a list in a session value - rather than changing or replacing the value completely - Django will not automatically know it needs to save the session. You need to tell it explicitly:

request.session.modified = True

See the docs on When sessions are saved.

Upvotes: 2

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

try :

del request.session['your key']

or

m = request.session.pop('your key')

Upvotes: 2

Related Questions