0
0
Djangoframework~5 mins

Setting and getting session data in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a session in Django?
A session in Django is a way to store data on the server side for a particular user across multiple requests. It helps keep user-specific information like login status or preferences.
Click to reveal answer
beginner
How do you set a session variable in a Django view?
You set a session variable by assigning a value to a key in the request.session dictionary, like request.session['key'] = value.
Click to reveal answer
beginner
How do you retrieve a session variable safely in Django?
Use request.session.get('key') to get the value. It returns None if the key does not exist, avoiding errors.
Click to reveal answer
intermediate
What happens if you try to access a session key that does not exist using request.session['key']?
Django raises a KeyError because the key is missing. To avoid this, use request.session.get('key').
Click to reveal answer
intermediate
How can you delete a session variable in Django?
Use del request.session['key'] to remove a session variable. This deletes the key and its value from the session data.
Click to reveal answer
Which of these is the correct way to set a session variable in Django?
Arequest.session['user'] = 'Alice'
Brequest.set_session('user', 'Alice')
Csession['user'] = 'Alice'
Drequest.session.set('user', 'Alice')
How do you safely get a session value that might not exist?
Arequest.session.get('key')
Brequest.session['key']
Crequest.get_session('key')
Drequest.session.fetch('key')
What error occurs if you access a missing session key with request.session['key']?
AValueError
BAttributeError
CTypeError
DKeyError
How do you delete a session variable named 'cart'?
Arequest.session.remove('cart')
Bdel request.session['cart']
Crequest.session['cart'] = None
Drequest.session.pop('cart')
Where is session data stored in Django by default?
AIn server-side files
BIn browser cookies
CIn the database
DIn local storage
Explain how to set, get, and delete session data in a Django view.
Think of request.session as a dictionary to store user data.
You got /3 concepts.
    Describe what happens if you try to access a session key that does not exist using request.session['key'] and how to avoid errors.
    Consider how dictionary access works in Python.
    You got /3 concepts.