[Fixed]-Testing a session variable

12👍

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'

36👍

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

0👍

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.

try:
    print(request.session['name'])
except KeyError:
    print('name variable is not set')

Leave a comment