0
0
Djangoframework~30 mins

Setting and getting session data in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Setting and Getting Session Data in Django
📖 Scenario: You are building a simple Django web app that tracks a user's favorite color during their visit. You want to store this color in the session so it remembers the choice as the user navigates pages.
🎯 Goal: Build a Django view that sets a session variable called favorite_color to a specific value, and another view that reads and displays this session value.
📋 What You'll Learn
Create a Django view function called set_color that sets request.session['favorite_color'] to the string 'blue'.
Create a Django view function called get_color that reads request.session['favorite_color'] and returns it in an HttpResponse.
Use the Django HttpResponse class to return simple text responses.
Ensure the session data is properly set and retrieved using Django's session framework.
💡 Why This Matters
🌍 Real World
Web apps often need to remember user preferences or temporary data during a visit. Sessions let you store this data securely on the server side.
💼 Career
Understanding session management is essential for backend web developers working with Django or similar frameworks to maintain user state and preferences.
Progress0 / 4 steps
1
Create the set_color view to set session data
Write a Django view function called set_color that takes request as a parameter and sets request.session['favorite_color'] to the string 'blue'. Return an HttpResponse with the text 'Color set to blue'.
Django
Need a hint?

Use request.session['favorite_color'] = 'blue' to store the color in the session.

2
Create the get_color view to read session data
Add a Django view function called get_color that takes request as a parameter and reads the session value request.session['favorite_color']. Return an HttpResponse with the text 'Favorite color is: ' followed by the session value.
Django
Need a hint?

Use color = request.session['favorite_color'] to get the stored color.

3
Add a check for missing session data in get_color
Modify the get_color view to use request.session.get('favorite_color', 'not set') to safely get the session value or return 'not set' if it does not exist. Return an HttpResponse with the text 'Favorite color is: ' followed by this value.
Django
Need a hint?

Use request.session.get('favorite_color', 'not set') to avoid errors if the session key is missing.

4
Add URL patterns for the views
Create a Django urlpatterns list with two path entries: one for set_color at URL 'set/' and one for get_color at URL 'get/'. Import path from django.urls and import the two view functions.
Django
Need a hint?

Use path('set/', set_color) and path('get/', get_color) inside urlpatterns.