Check if Session Key is set
I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:
You can do:
if key not in request.session: # Set it.
In your case:
if 'cart' not in request.session: # Set it.
EDIT: changed the code snippet to use key not in
rather than not key in
. Thanks @katrielalex.
You can use the get
-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value:
cart = request.session.get('cart')cart = request.session.get('cart', 'no cart')