[Fixed]-Testing a session variable


get will do all the work for you. Check if the key exists, if not then the value is None

if request.session.get('name', None) == "dummy":
    print 'name is = dummy'


Treat it as a Python dictionary:

if 'name' in request.session:
    print request.session['name']

How to use sessions: Django documentation: How to use sessions


Another way of doing this is put it in try.

In this the third example code snippet

if you apply del operation in a session variable it which does not exist, so it throws KeyError.

so check it like this.

except KeyError:
    print('name variable is not set')

Leave a comment