Deepend
Deepend

Reputation: 4155

How to store and access values stored in a Session Object on separate form pages

I am beginning to learn about Session Objects and I have come across an issue which I am sure is very simple.

I thought the idea of a session object was to store a variable so that it could be accessed later? In the below abated piece of code the first print statement works as expected printing "This is self request 2" but the second causes this error:

Exception Type: KeyError

Exception Value: 0 Exception Location: /Library/Python/2.7/site-packages/django/contrib/sessions/backends/base.py in getitem, line 47

Why is the second print statement not working? Why can I not access self.request.session[0] on the second step of my form?

Any help/tips are much appreciated

Thanks

Code

class SurveyWizardOne(SessionWizardView):    

    def get_context_data(self, form, **kwargs):
        context = super(SurveyWizardOne, self).get_context_data(form, **kwargs)  
        if self.steps.current in ['5','6','7','8','9']:
            step = int(self.steps.current)

            if step in (5, 6, 7):

                self.request.session[0] = 2   
                print 'This is self request', self.request.session[0]                 

            elif step == 8:                   

                print 'This is STILL self request', self.request.session[0]

        return context 

Upvotes: 0

Views: 4749

Answers (1)

Mounir
Mounir

Reputation: 11726

Try to use keys to store values:

request.session['fav_color'] = 'red' #Set the value
fav_color = request.session.get('fav_color', 'red') #Read the value else read a default one

From Django Doc: A wrapper around the JSON serializer from django.core.signing. Can only serialize basic data types.

In addition, as JSON supports only string keys, note that using non-string keys in request.session won’t work as expected

Upvotes: 2

Related Questions