In Django, sessions help keep track of user data between requests. Why is this important?
Think about how HTTP treats each page load independently.
HTTP does not remember anything between requests. Sessions let Django remember who the user is and store data like login status.
Consider this Django view snippet:
def set_session(request):
request.session['fav_color'] = 'blue'
return HttpResponse('Session set')What will happen after this view runs?
Think about how Django links session data to users.
Django stores session data on the server and sends a session ID cookie to the browser to identify the user on future requests.
Given this Django view:
def counter(request):
count = request.session.get('count', 0)
count += 1
request.session['count'] = count
return HttpResponse(f'Count is {count}')If a user visits this view 3 times in a row, what will be the response on the third visit?
Remember the session keeps data between requests.
Each visit increments the 'count' stored in the session. After three visits, the count will be 3.
Which of the following Django code snippets will cause an error when trying to set a session variable?
def set_session(request): # Options below
Check how session data is accessed and set.
Session data is accessed like a dictionary, so using dot notation causes an AttributeError.
A developer notices that session data is lost after redirecting to another view. Which of the following is the most likely cause?
Think about when Django saves session changes.
Django saves session data only if the session is modified before the response is returned. Returning early can skip saving.