I’ve been coding in Django for nearly 2 years now and only recently have I needed to code a session variable.
It is probably because sessions are mainly to do with login and that was handled by the django-allauth plugin that I use.
However the situation arose where I needed to store a session variable to remember the user’s last choice (their last_pick) from a number of options.
Setting a session variable in Django
The session variable is a dict. So assigning is easy. Let’s pretend they are picking a fruit.
request.session['last_pick'] = 'apple'
Getting a session variable in Django
Getting a variable needs an extra step – you can’t just reference request.session[‘last_pick’] – as it might not be set. This causes an error. So we use the get() method with a default as the second argument.
last_pick = request.session.get('last_pick', None)
Then down the track you might do something like:
if last_pick:
# do something knowing last_pick is populated e.g.
option_to_show = last_pick
else:
# do something knowing there is no last_pick e.g.
option_to_show = some_function_to_get_the_default_option()
# Set the last pick to the default
request.session['last_pick'] = option_to_show
...
# Now do something with the option we have to show
print(f"Item picked was: {last_pick}")
The get() method for a dict
I missed learning about the get() method when first learning Python. It was only long down the track did I learn of it’s existence. Here it is for your reference:
dictionary.get(keyname, value)
Parameter | Description |
---|---|
keyname | Required. The keyname of the item you want to return the value from |
value | Optional. A value to return if the specified key does not exist. Default value None |
Django Docs
And finally, a link to the Django Docs on sessions – You’re welcome!