Bird
Raised Fist0
Djangoframework~20 mins

Setting and getting session data in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Session Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Django view when session key 'count' is not set?

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?

Django
def my_view(request):
    count = request.session.get('count', 0)
    count += 1
    request.session['count'] = count
    return HttpResponse(f"Count is {count}")
ACount is None
BCount is 0
CCount is 1
DKeyError: 'count'
Attempts:
2 left
💡 Hint

Remember the default value used in get when the key is missing.

📝 Syntax
intermediate
1:30remaining
Which option correctly sets a session variable 'user' to 'alice' in Django?

Choose the correct code snippet to set the session key 'user' to the string 'alice' inside a Django view.

Arequest.session.add('user', 'alice')
Brequest.session['user'] = 'alice'
Crequest.session.set('user', 'alice')
Drequest.session.user = 'alice'
Attempts:
2 left
💡 Hint

Think about how Python dictionaries are used to set session data.

🔧 Debug
advanced
2:30remaining
Why does this Django view fail to save session data?

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?

Django
def view(request):
    request.session['visits'] = request.session.get('visits', 0) + 1
    return HttpResponse(f"Visits: {request.session['visits']}")
ASession middleware is not enabled in settings
BThe view does not call request.session.save() explicitly
CHttpResponse does not support f-strings
DThe session key 'visits' is read-only
Attempts:
2 left
💡 Hint

Check if the session system is properly activated in Django.

state_output
advanced
2:00remaining
What is the session data after this sequence of requests?

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?

Django
def counter(request):
    if 'count' not in request.session:
        request.session['count'] = 0
    request.session['count'] += 2
    return HttpResponse(str(request.session['count']))
A6
B2
C3
D0
Attempts:
2 left
💡 Hint

Count how much the value increases each request.

🧠 Conceptual
expert
2:30remaining
Which statement about Django session data is true?

Choose the correct statement about how Django handles session data.

ASession data is stored client-side in cookies by default
BSession data requires explicit saving by calling request.session.save() after modification
CSession data is automatically encrypted and cannot be read by the server
DSession data is stored server-side and linked to the client via a session cookie
Attempts:
2 left
💡 Hint

Think about where Django keeps session data and how it identifies clients.

Practice

(1/5)
1. What is the correct way to store a user's favorite color in Django session inside a view?
easy
A. request.session['favorite_color'] = 'blue'
B. request.session.set('favorite_color', 'blue')
C. session['favorite_color'] = 'blue'
D. request.set_session('favorite_color', 'blue')

Solution

  1. Step 1: Understand Django session assignment

    In Django, session data is stored by assigning a value to a key in request.session like a dictionary.
  2. Step 2: Identify correct syntax for setting session data

    The correct syntax is request.session['key'] = value. Methods like set or set_session do not exist.
  3. Final Answer:

    request.session['favorite_color'] = 'blue' -> Option A
  4. Quick Check:

    Set session data with dictionary syntax [OK]
Hint: Use dictionary style assignment to set session data [OK]
Common Mistakes:
  • Using non-existent methods like set() or set_session()
  • Trying to assign session data without request.session
  • Using session variable without request object
2. Which of the following is the correct syntax to retrieve a session value safely with a default in Django?
easy
A. request.session.get('user_id' : None)
B. request.session['user_id', None]
C. request.session.fetch('user_id', None)
D. request.session.get('user_id', None)

Solution

  1. Step 1: Recall the method to get session data safely

    Django sessions use the dictionary method get(key, default) to retrieve values safely without error if key is missing.
  2. Step 2: Identify correct syntax

    The correct syntax is request.session.get('user_id', None). Using brackets with comma or colon is invalid syntax, and fetch is not a valid method.
  3. Final Answer:

    request.session.get('user_id', None) -> Option D
  4. Quick Check:

    Use get() with key and default [OK]
Hint: Use get() method with key and default to avoid errors [OK]
Common Mistakes:
  • Using brackets with comma or colon inside session access
  • Using non-existent fetch() method
  • Accessing session key directly without default causing KeyError
3. Given the following Django view code snippet, what will be the output if the session has no 'visits' key initially?
def my_view(request):
    visits = request.session.get('visits', 0)
    visits += 1
    request.session['visits'] = visits
    return HttpResponse(f"Visit count: {visits}")
medium
A. Visit count: None
B. Visit count: 0
C. Visit count: 1
D. KeyError exception

Solution

  1. Step 1: Understand default value usage in get()

    The code uses request.session.get('visits', 0) which returns 0 if 'visits' key is missing.
  2. Step 2: Follow the increment and assignment

    It adds 1 to visits (0 + 1 = 1), then stores it back in session and returns the string with visits value.
  3. Final Answer:

    Visit count: 1 -> Option C
  4. Quick Check:

    Default 0 + 1 increment = 1 [OK]
Hint: Default value in get() prevents KeyError, then increment [OK]
Common Mistakes:
  • Assuming visits starts at None or causes error
  • Forgetting to add 1 before storing
  • Expecting KeyError when key is missing
4. Identify the error in this Django view code that tries to get a session value:
def view(request):
    user = request.session['user', 'guest']
    return HttpResponse(user)
medium
A. TypeError because session is not subscriptable
B. KeyError if 'user' key missing
C. Returns 'guest' string correctly
D. SyntaxError due to incorrect session key access

Solution

  1. Step 1: Analyze session key access syntax

    The code uses request.session['user', 'guest'] which passes a tuple ('user', 'guest') as the key.
  2. Step 2: Identify correct way to provide default

    This raises KeyError if the tuple key is missing. To get 'user' with default 'guest', use request.session.get('user', 'guest').
  3. Final Answer:

    KeyError if 'user' key missing -> Option B
  4. Quick Check:

    Tuple in brackets causes KeyError [OK]
Hint: Use get() for default, not tuple keys in brackets [OK]
Common Mistakes:
  • Using tuple inside brackets for session key
  • Expecting bracket syntax to accept default value
  • Confusing dictionary get() method with bracket access
5. You want to track a user's last visited page URL in session and display it on the next page visit. Which code snippet correctly sets and gets this session data in Django?
hard
A. last = request.session.get('last_page', 'None'); request.session['last_page'] = request.path
B. request.session['last_page'] = request.path; last = request.session.get('last_page', 'None')
C. request.session.set('last_page', request.path); last = request.session['last_page']
D. last = request.session['last_page']; request.session['last_page'] = request.path

Solution

  1. Step 1: Understand the order of getting and setting session data

    To show the last visited page, first get the stored value, then update it with the current page path.
  2. Step 2: Identify correct code order and methods

    last = request.session.get('last_page', 'None'); request.session['last_page'] = request.path first retrieves last_page with a default, then updates it with request.path. Other options set before getting or use invalid methods.
  3. Final Answer:

    last = request.session.get('last_page', 'None'); request.session['last_page'] = request.path -> Option A
  4. Quick Check:

    Get old value before updating session [OK]
Hint: Get session value before updating it to show previous data [OK]
Common Mistakes:
  • Setting session before getting old value loses previous data
  • Using non-existent set() method
  • Accessing session key directly without default causing error