0
0
Djangoframework~30 mins

Why sessions matter in Django - See It in Action

Choose your learning style9 modes available
Why sessions matter
📖 Scenario: You are building a simple Django web app where users can add items to a shopping cart. Since HTTP is stateless, the app needs a way to remember the cart contents as the user browses different pages.Sessions help keep track of user data between requests without requiring login. This project will show how to use Django sessions to store and retrieve cart items.
🎯 Goal: Build a Django view that uses sessions to store a list of cart items. The user can add items, and the session remembers them across page visits.
📋 What You'll Learn
Create a Django view function called add_to_cart that adds an item to the session cart list.
Initialize the cart list in the session if it does not exist.
Add a new item string to the session cart list.
Save the session after updating the cart.
Return a simple HTTP response confirming the item was added.
💡 Why This Matters
🌍 Real World
Websites use sessions to remember user data like shopping carts, login status, or preferences across multiple pages.
💼 Career
Understanding sessions is essential for backend web developers to manage user state and build interactive web applications.
Progress0 / 4 steps
1
Set up the initial Django view function
Create a Django view function called add_to_cart that takes request as a parameter and returns an HttpResponse with the text 'Item added to cart'. Import HttpResponse from django.http.
Django
Need a hint?

Remember to import HttpResponse and define a function named add_to_cart that returns a simple response.

2
Initialize the cart list in the session
Inside the add_to_cart function, check if 'cart' exists in request.session. If not, create it as an empty list. Use if 'cart' not in request.session: and set request.session['cart'] = [].
Django
Need a hint?

Use if 'cart' not in request.session: to check and then assign an empty list to request.session['cart'].

3
Add an item to the session cart list
Still inside add_to_cart, append the string 'apple' to the request.session['cart'] list. Use request.session['cart'].append('apple').
Django
Need a hint?

Use the append method on request.session['cart'] to add the string 'apple'.

4
Save the session after updating the cart
After appending the item, call request.session.modified = True to tell Django the session data changed. Keep the existing return statement.
Django
Need a hint?

Set request.session.modified = True after changing the session list to save changes.