I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there anyway to check if a session is set, so that it can be set if it doesn't exist?
+3
A:
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.
Manoj Govindan
2010-10-11 18:02:42
The pythonic way would be `if key not in request.session`.
katrielalex
2010-10-11 19:29:49
+1
A:
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')
lazerscience
2010-10-11 18:16:52