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 any way to check if a session is set, so that it can be set if it doesn't exist?
You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable. For example: <?
Use request. getSession(false) to check if a user has a session. With this method you don't create a new session if you're going to render a view based on if a user is authenticated or not.
If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.
Make use of isset() function to check if session variable is already set or not.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With