Sessions help websites remember who you are as you move around. They keep your information safe and make your experience smooth.
When a user logs into a website and you want to keep them logged in as they browse.
When you want to save items in a shopping cart before checkout.
When you need to remember user preferences like language or theme.
When you want to track user activity without asking them to log in again.
When you want to protect sensitive data by storing it securely on the server.
Syntax
Django
request.session['key'] = 'value'
value = request.session.get('key', 'default')
del request.session['key']
Sessions store data on the server, not in the user's browser, making it safer.
You access session data through the request object in Django views.
Examples
Save the username 'alice' in the session to remember the user.
Django
request.session['username'] = 'alice'
Get the shopping cart from the session or start with an empty list if none exists.
Django
cart = request.session.get('cart', [])
Remove the username from the session, for example when the user logs out.
Django
del request.session['username']
Sample Program
This Django view counts how many times a user visits the page by saving a number in the session. Each time the page loads, it increases the count and shows it.
Django
from django.http import HttpResponse
def visit_counter(request):
count = request.session.get('visit_count', 0)
count += 1
request.session['visit_count'] = count
return HttpResponse(f"You have visited this page {count} times.")
OutputSuccess
Important Notes
Sessions rely on cookies to link the user to their stored data.
Session data is stored on the server, so it is more secure than storing data in the browser.
Always clear session data when it is no longer needed to keep things tidy.
Summary
Sessions let websites remember users and their data safely.
They are useful for login, carts, preferences, and tracking.
Django makes sessions easy to use with simple syntax.
Practice
(1/5)
1. Why do Django sessions matter in web development?
easy
A. They change the website's design dynamically.
B. They speed up the website loading time.
C. They automatically fix bugs in the code.
D. They let websites remember user data between requests.
Solution
Step 1: Understand what sessions do
Sessions store user data temporarily so the website can remember users across different pages or visits.
Step 2: Identify the main purpose of sessions
Sessions help keep track of things like login status, shopping carts, or preferences, which means remembering user data is their key role.
Final Answer:
They let websites remember user data between requests. -> Option D
Quick Check:
Sessions remember user data = A [OK]
Hint: Sessions remember user info across pages [OK]
Common Mistakes:
Thinking sessions speed up loading
Believing sessions fix code bugs
Confusing sessions with design changes
2. Which of the following is the correct way to set a session variable in Django?
easy
A. request.session['user'] = 'Alice'
B. request.set_session('user', 'Alice')
C. session['user'] = 'Alice'
D. request.session.set('user', 'Alice')
Solution
Step 1: Recall Django session syntax
In Django, session variables are set using dictionary-like syntax on request.session.
Step 2: Match the correct syntax
The correct way is request.session['key'] = value, so request.session['user'] = 'Alice' is valid.
Final Answer:
request.session['user'] = 'Alice' -> Option A
Quick Check:
Set session with dictionary syntax = C [OK]
Hint: Use request.session like a dictionary to set values [OK]
Common Mistakes:
Using request.set_session instead of request.session
Trying to set session without request object
Using method calls instead of dictionary syntax
3. What will be the output of this Django view code snippet?
The code uses request.session.get('count', 0) to get the current count or 0 if not set.
Step 2: Calculate the new count value
It adds 1 to the current count, so the first time this runs, count becomes 1.
Final Answer:
Count: 1 -> Option B
Quick Check:
Initial count 0 + 1 = 1 [OK]
Hint: Session get returns default if key missing [OK]
Common Mistakes:
Assuming count starts at 0 output
Expecting string 'count' instead of number
Thinking session must be manually created first
4. Identify the error in this Django session code:
def view(request):
request.session['user'] = 'Bob'
del request.session['user']
return HttpResponse(request.session['user'])
medium
A. KeyError because 'user' is deleted before access
B. No error, code works fine
C. SyntaxError in session deletion
D. Session data cannot be deleted
Solution
Step 1: Analyze session deletion
The code deletes the 'user' key from session using del request.session['user'].
Step 2: Check access after deletion
After deletion, it tries to access request.session['user'], which no longer exists, causing a KeyError.
Final Answer:
KeyError because 'user' is deleted before access -> Option A
Quick Check:
Access deleted key causes KeyError = B [OK]
Hint: Don't access session keys after deleting them [OK]
Common Mistakes:
Thinking deletion syntax is wrong
Assuming session keys can't be deleted
Ignoring KeyError on missing keys
5. You want to track a user's favorite color across visits using Django sessions. Which approach correctly saves and retrieves this data?
def set_color(request):
color = request.GET.get('color')
if color:
# Save color in session
...
return HttpResponse('Color saved')
def get_color(request):
# Retrieve color from session
...
return HttpResponse(f'Favorite color: {color}')
hard
A. set_color: session['color'] = color; get_color: color = session.get('color')
B. set_color: request.session.set('color', color); get_color: color = request.session['color']
C. set_color: request.session['color'] = color; get_color: color = request.session.get('color', 'unknown')
D. set_color: request.session.color = color; get_color: color = request.session.color
Solution
Step 1: Correctly save session data
Use dictionary syntax: request.session['color'] = color to save the value.
Step 2: Safely retrieve session data
Use request.session.get('color', 'unknown') to get the color or default if missing.
Final Answer:
set_color: request.session['color'] = color; get_color: color = request.session.get('color', 'unknown') -> Option C
Quick Check:
Use dict syntax and get() for safe access = D [OK]
Hint: Use dict syntax and get() to handle missing keys [OK]
Common Mistakes:
Using session.set() method which doesn't exist
Trying to access session attributes like object properties
Using undefined session variable without request
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.