0
0
Djangoframework~10 mins

Why sessions matter in Django - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the session middleware in Django settings.

Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    [1],
    'django.middleware.common.CommonMiddleware',
]
Drag options to blanks, or click blank then click option'
A'django.middleware.locale.LocaleMiddleware'
B'django.middleware.csrf.CsrfViewMiddleware'
C'django.contrib.sessions.middleware.SessionMiddleware'
D'django.middleware.clickjacking.XFrameOptionsMiddleware'
Attempts:
3 left
💡 Hint
Common Mistakes
Using CSRF middleware instead of session middleware
Forgetting to include session middleware in settings
2fill in blank
medium

Complete the code to set a session variable in a Django view.

Django
def my_view(request):
    request.session[[1]] = 'blue'
    return HttpResponse('Color set')
Drag options to blanks, or click blank then click option'
A'favorite_color'
B'user_id'
C'session_key'
D'csrf_token'
Attempts:
3 left
💡 Hint
Common Mistakes
Using reserved keys like 'csrf_token'
Using variable names instead of string keys
3fill in blank
hard

Fix the error in this code to retrieve a session variable safely.

Django
def get_color(request):
    color = request.session.get([1], 'red')
    return HttpResponse(f'Color is {color}')
Drag options to blanks, or click blank then click option'
A'favorite_color'
Bfavorite_color
Ccolor
D'color'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without quotes as keys
Forgetting to provide a default value
4fill in blank
hard

Fill both blanks to check if a session key exists and then delete it.

Django
if [1] in request.session:
    [2] request.session['user_id']
Drag options to blanks, or click blank then click option'
A'user_id'
Bdel
Cremove
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without quotes as keys
Using incorrect keywords like 'remove' or 'delete' which don't exist in Python
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that stores word lengths in session if length is greater than 3.

Django
request.session['word_lengths'] = { [1]: len([2]) for [2] in words if len([2]) [3] 3 }
Drag options to blanks, or click blank then click option'
Aword
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the comprehension
Using '<' instead of '>' for filtering