Consider this Django view that tries to read a session key 'count' and increments it:
def my_view(request):
count = request.session.get('count', 0)
count += 1
request.session['count'] = count
return HttpResponse(f"Count is {count}")What will the response content be on the first visit?
def my_view(request): count = request.session.get('count', 0) count += 1 request.session['count'] = count return HttpResponse(f"Count is {count}")
Remember the default value used in get when the key is missing.
The session key 'count' is not set initially, so get('count', 0) returns 0. Then it increments to 1 and saves back. So the response shows 'Count is 1'.
Choose the correct code snippet to set the session key 'user' to the string 'alice' inside a Django view.
Think about how Python dictionaries are used to set session data.
Session data in Django behaves like a dictionary. You set values by assigning to keys with square brackets. Methods like set or add do not exist on session objects.
Look at this Django view:
def view(request):
request.session['visits'] = request.session.get('visits', 0) + 1
return HttpResponse(f"Visits: {request.session['visits']}")After calling this view multiple times, the visit count does not increase. What is the most likely reason?
def view(request): request.session['visits'] = request.session.get('visits', 0) + 1 return HttpResponse(f"Visits: {request.session['visits']}")
Check if the session system is properly activated in Django.
If the session middleware is missing from MIDDLEWARE in settings, session data won't persist. The view code is correct and does not require explicit save calls.
Assume a user makes these requests to a Django view that manages session data:
def counter(request):
if 'count' not in request.session:
request.session['count'] = 0
request.session['count'] += 2
return HttpResponse(str(request.session['count']))What will be the session value for 'count' after the third request?
def counter(request): if 'count' not in request.session: request.session['count'] = 0 request.session['count'] += 2 return HttpResponse(str(request.session['count']))
Count how much the value increases each request.
Initially 'count' is set to 0. Each request adds 2. After 3 requests: 0 + 2 + 2 + 2 = 6.
Choose the correct statement about how Django handles session data.
Think about where Django keeps session data and how it identifies clients.
Django stores session data on the server side (database, cache, or file). The client only holds a session ID cookie to link to that data. The server can read session data. It does not require explicit save calls.