18

I came across Django request.session; I know how to set and test it for a specific value.

request.session['name'] = "dummy"

and somewhere I check

if request.session['name'] == "dummy" :
   #do something

But, now I have to check whether the session variable was even set in the first place? I mean how can I check whether there exists a value in the request.session['name'] is set?

Is there a way to check it?

3 Answers3

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

Lars Wiegman
  • 2,397
  • 1
  • 16
  • 13
  • 2
    This is a much cleaner solution, compared to the accepted answer. – tokyovariable Apr 30 '15 at 01:43
  • Related question. If I had another dictionary in the session variable e.g. {'b': {'z': 100}}, will I need to use multiple if statements? Assume that the variables may not exist (so in the previous example, 'b' and 'z' may not exist) – wasabigeek Dec 27 '15 at 14:03
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'
tokyovariable
  • 1,656
  • 15
  • 23
programmersbook
  • 3,914
  • 1
  • 20
  • 13
  • 1
    request.session.get('name') should be enough – Jerzyk May 06 '11 at 10:23
  • In many cases you will not know what the value in the session will be e.g. some tokens, login sessions etc. (this is regarding the way you equated it with a fixed string "dummy") – Zeeshan Jan 31 '20 at 03:43
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')
Siraj Alam
  • 9,217
  • 9
  • 53
  • 65