django - sessions not save for some reason when I go back to the same page using a link

4.7k views Asked by At

In one of my views I'm saving a few sessions like this:

def myview(request):
    request.session['session_1'] = 'value1
    request.session['session_2'] = 'value2'

Then on the same view function and also other views found on other applications I'm trying to get the session values like this:

   session_value1 = request.session['session_1'] 
   session_value2 = request.session['session_2']

I would like the values for the 'session_1' and 'session_2' to never expire and also be available anywhere on the web site (like other views on the same application and views on other applications).

My problem is that when I'm on the same page/view (just described above) when I do a refresh to the page I have to problems retrieving session_1 and session_2 values. But let's say if I go to a different page and then come back to the original page the 'session_1' and 'session_2' values are gone. Also the values of the 'session_1' and 'session_2' are not available on any other page/view.

I have no settings for sessions on my settings.py so all the values for sessions are the default ones.

Any thoughts why the sessions are not saved? Thank you!

1

There are 1 answers

5
Yuji 'Tomita' Tomita On BEST ANSWER

My problem is that when I'm on the same page/view (just described above) when I do a refresh to the page I have to problems retrieving session_1 and session_2 values.

So you are setting and retrieving on the same view? Can I see that view? Are you literally assigning 'value1' or is there otherwise any chance your view is causing problems?

Is the session_key the same between page views?

Copy and paste this into your root urls.py and visit /session-test/

from django import http

def session_test_1(request):
    request.session['test'] = 'Session Vars Worked!'
    return http.HttpResponseRedirect('done/?session=%s' % request.session.session_key)

def session_test_2(request):
    return http.HttpResponse('<br>'.join([
        request.session.session_key,
        request.GET.get('session'),
        request.session.get('test', 'Session is Borked :(')
         ]))


urlpatterns += patterns('',
        (r'^session-test/$', session_test_1),
        (r'^session-test/done/$', session_test_2),
)