Roshan Bagdiya
Roshan Bagdiya

Reputation: 2178

How to set new value for a key in Django Session_data

What I have in my encoded session_data is:

'workspaceKey':'8d7f4b3106c740c1a54970a8b67d156d', 
'_auth_user_hash': '7e024dd67ccb0e2aaab9ac1a92887109f7f020e4', 
'_auth_user_id': '1', 
'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend'

What I have tried is (1st approach):

request.session['workspaceKey'] = "123f4b3106c740c1a54970a8b67d111d"

but it is not updating workspaceKey is my existing session_data

Another approach what I tried is:

sessionid = Session.objects.get(session_key=session_key)
sessionid.get_decoded()['workspaceKey'] = "8d7f4b3106c740c1a54970a8b67d111d"

Again it is not updating workspaceKey is my existing session_data. I have also tried below combinations with respect to above approach

request.session.modified = True 
SESSION_SAVE_EVERY_REQUEST=False

My code is like this

session_key = request.data['sessionKey'] 
request.session['workspaceKey']= "somenewkey" 
request.session.modified = True 
sessionid = Session.objects.get(session_key=session_key) 
session_data= sessionid.get_decoded()
print session_data

What I expect in my output as (new workspace key should be updated)

'workspaceKey':'123f4b3106c740c1a54970a8b67d111d', 
'_auth_user_hash': '7e024dd67ccb0e2aaab9ac1a92887109f7f020e4', 
'_auth_user_id': '1', 
'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend'

Upvotes: 0

Views: 3335

Answers (2)

Roshan Bagdiya
Roshan Bagdiya

Reputation: 2178

Below code works perfectly in order to change session_data of django session table. Re-encoding the updated key of session_data provides updated session_data.So the key point is after decoding data encoding is must.

from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore
workspaceKey ="123f4b3106c740c1a54970a8b67d111d"
session_key = request.data['sessionKey']
sessionid = Session.objects.get(session_key=session_key)
session_data= sessionid.get_decoded()
print session_data['workspaceKey']
session_data['workspaceKey']= workspaceKey
encoded_data = SessionStore().encode(session_data)
sessionid.session_data = encoded_data
sessionid.save()

Upvotes: 5

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

You need to save and after you should fetch that session from db and decode that encrypted session will give you need updated session value.

Try below code that will give new session data

from django.contrib.sessions.models import Session
session_key = request.data['sessionKey'] 
request.session['workspaceKey']= "somenewkey" 
request.session.save()
session_obj = Session.objects.get(session_key=request.session.session_key).get_decoded()
print session_obj

Upvotes: 5

Related Questions