Why is Editing SessionStore Between Views in Django not Working

28 views Asked by At

I have a session in django using django.sessions that I wish to alter using the SessionStore, but when I alter the Store and refresh the page (which is naturally updated by django's session middleware), the values are not persisted.

For example, here is my initial response, I set the cookies so I can gather the SessionStore in the next view (it may seem off to use Cookies and Sessions together like this, but I have my reasons not related to this post, I am not able to access django.sessions from the view I initially gather the cookies from):

next = f"{request.path}"
response = redirect(f"{reverse('quickbooks_authentication', args=[request.client_url])}?quickbooks_account_id={quickbooks_account.pk}&next={next}")
response.set_cookie('session_key', request.session.session_key)
response.set_cookie('client_url', client_url)
return response

Then in the next view, all is printing out as expected:

print(request.COOKIES.get('session_key')) # tmcdnowypuzcrndtw117hnjxgsruzddj --valid

store = SessionStore(session_key=request.COOKIES.get('session_key'))

store['testing'] = 'test'
store.save()
print(store.modified)  # True
print(store['testing'])  # test

return redirect(request.GET.get('next'))

But when I go back to the page, the session was not updated as store['testing'] does not exist. Why, what am I doing wrong?

store = SessionStore(session_key=request.COOKIES.get('session_key'))  # same key as before
store['testing']  # key error
1

There are 1 answers

0
ViaTech On BEST ANSWER

It seems silly to me as there is a new query for the SessionStore in both views using SessionStore(session_key=request.COOKIES.get('session_key')), but the solution was to set the actual request.session to the newly defined/updated Store, like so:

...
store['testing'] = 'test'
store.save()
# tah dah, now we are good on reload
request.session = store

With that change, I am able to view the session changes, along with the default values I already had between the SessionStore(session_key=request.COOKIES.get('session_key')) object and now request.session