Cart changes vanish after redirect
Likely cause: Only a nested session dictionary was mutated.
Check and correct: Assign the updated dictionary back to request.session["cart"].
PROJECT 6 · LESSON 11 OF 16
Persist product selections in a Django session and calculate totals from database prices.
Continue from lesson 10: Make tasks private and test access rules. Keep existing files; create or replace the complete files listed below.
Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.
A guest should be able to collect products before creating an account. A session cart demonstrates temporary per-browser state while keeping authoritative product information in the database.
The default session backend stores session data in the database; the browser holds a session identifier cookie. This differs from the Next.js localStorage exercise. A guest can have a session without a user account.
The cart stores only product IDs and quantities. Names, prices and availability come from Product on each server render. A cart does not reserve inventory.
The cart stores a mapping from product ID strings to integer quantities. It does not store trusted prices, names or totals. Each display loads current product records and calculates line totals with Decimal. A browser cannot obtain a lower price by sending an extra price field.
Session serialization favors simple JSON-compatible values. Dictionary keys become strings, which is why product IDs are normalized. Quantities must be positive bounded integers. A session value is still input to validate: old application versions or malformed state can leave unexpected shapes.
Adding an item records intent, not ownership of stock. Another customer may buy it before checkout. The cart display can flag unavailable products, but checkout must re-read and verify every product inside a transaction. Moving that guarantee into the add button would leave a race between browsing and purchase.
A current price may change between visits. This course deliberately uses current database prices for cart display and final server-side checkout. An order, once created, stores a snapshot so later price edits cannot rewrite purchase history. State clearly when a number is provisional and when it becomes an order record.
Assign the updated dictionary back to request.session["cart"]. Mutating only a nested dictionary may not mark the session as modified. The helper makes writes explicit and keeps parsing and calculation behavior out of individual views.
Cart actions use POST plus CSRF protection. require_POST returns 405 for a GET mutation request. The add action limits unique products and quantity, reports problems with messages and redirects to a readable cart page. None of those limits replace the stock validation at checkout.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
A visitor submits the product add form.
The view verifies POST and retrieves an active product.
The helper reads and validates the session cart.
The updated ID-to-quantity map is assigned back to the session.
A cart GET loads current products and calculates Decimal line totals and a total.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
Interpret session selections and derive a current catalog summary.
from decimal import Decimal
from .models import Product
def read_cart(request):
raw = request.session.get("cart", {})
if not isinstance(raw, dict):
return {}
return {key: quantity for key, quantity in raw.items()
if isinstance(key, str) and key.isdigit() and len(key) < 19
and isinstance(quantity, int) and not isinstance(quantity, bool) and 1 <= quantity <= 10}
def cart_summary(request):
cart = read_cart(request)
products = {str(p.pk): p for p in Product.objects.filter(pk__in=cart, active=True)}
lines = []
total = Decimal("0.00")
unavailable = False
for key, quantity in cart.items():
product = products.get(key)
line_total = product.price * quantity if product else Decimal("0.00")
unavailable = unavailable or product is None or (product is not None and quantity > product.stock)
lines.append({"id": key, "product": product, "quantity": quantity, "total": line_total})
total += line_total
return {"lines": lines, "subtotal": total, "unavailable": unavailable}
Add an integer quantity form alongside the enquiry form.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=80)
email = forms.EmailField()
message = forms.CharField(min_length=10, max_length=1000, widget=forms.Textarea)
class CartQuantityForm(forms.Form):
quantity = forms.IntegerField(min_value=1, max_value=10)
Allow guest users to add available products through POST.
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from .cart import read_cart, cart_summary
from .forms import CartQuantityForm
from .models import Product
def cart_detail(request):
return render(request, "shop/cart.html", cart_summary(request))
@require_POST
def cart_add(request, pk):
product = get_object_or_404(Product, pk=pk, active=True)
cart = read_cart(request)
key = str(product.pk)
quantity = cart.get(key, 0) + 1
if quantity > min(product.stock, 10) or (key not in cart and len(cart) >= 50):
messages.error(request, "Cannot add more: check stock or cart limits.")
else:
cart[key] = quantity
request.session["cart"] = cart
messages.success(request, "Added to cart.")
return redirect("shop:cart")
Expose the cart page and its add action.
from django.urls import path
from . import views, cart_views
app_name = "shop"
urlpatterns = [
path("", views.home, name="home"),
path("about/", views.about, name="about"),
path("hello/<str:name>/", views.greeting, name="greeting"),
path("cart/", cart_views.cart_detail, name="cart"),
path("cart/add/<int:pk>/", cart_views.cart_add, name="cart-add"),
path("products/", views.products, name="products"),
path("products/<slug:slug>/", views.product_detail, name="product-detail"),
path("contact/", views.contact, name="contact"),
]
Provide the shared HTML document, navigation and content slots.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}EduShop{% endblock %}</title>
<link rel="stylesheet" href="{% static 'shop/site.css' %}">
</head>
<body>
<nav aria-label="Main navigation">
<a href="{% url 'shop:home' %}">Home</a>
<a href="{% url 'shop:about' %}">About</a>
<a href="{% url 'shop:contact' %}">Contact</a>
<a href="{% url 'shop:products' %}">Products</a>
<a href="{% url 'tasks:list' %}">Tasks</a>
<a href="{% url 'shop:cart' %}">Cart</a>
{% if user.is_authenticated %}
<span>Hello, {{ user.username }}</span>
<form method="post" action="{% url 'logout' %}">{% csrf_token %}<button>Sign out</button></form>
{% else %}<a href="{% url 'login' %}">Sign in</a><a href="{% url 'signup' %}">Register</a>{% endif %}
</nav>
{% for message in messages %}<p role="status">{{ message }}</p>{% endfor %}
<main>{% block content %}{% endblock %}</main>
<footer>EduShop · Built while learning Django</footer>
</body>
</html>
Add a CSRF-protected action to the product page.
{% extends "base.html" %}
{% block title %}{{ product.name }} · EduShop{% endblock %}
{% block content %}<h1>{{ product.name }}</h1><p>{{ product.description }}</p><p>₹{{ product.price }}</p><p>{{ product.stock }} available</p>{% if product.stock %}<form method="post" action="{% url 'shop:cart-add' product.pk %}">{% csrf_token %}<button>Add to cart</button></form>{% endif %}{% endblock %}
Display the summary supplied by the cart service.
{% extends "base.html" %}
{% block content %}<h1>Your cart</h1>
{% for line in lines %}<article><h2>{{ line.product.name|default:"Unavailable product" }}</h2><p>Quantity: {{ line.quantity }} · ₹{{ line.total }}</p></article>{% empty %}<p>Your cart is empty.</p>{% endfor %}
<p>Subtotal: ₹{{ subtotal }}</p>{% if unavailable %}<p>Some items are unavailable or exceed current stock. Update the cart before checkout.</p>{% endif %}
{% endblock %}
Change a product price in admin after adding it to a cart.
The next cart display uses the new price.
The session stores choices. The database remains the authority for the current catalog price; order snapshots arrive later.
Never save a browser-submitted price as the authoritative order price.
Likely cause: Only a nested session dictionary was mutated.
Check and correct: Assign the updated dictionary back to request.session["cart"].
Likely cause: A Decimal total was put into the session.
Check and correct: Store only product IDs and integer quantities, and calculate money when reading products.
Add an item-count badge derived from the sum of quantities.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
No. It is a temporary choice. The final checkout transaction validates and changes stock.
It is not a simple serializable value and would become stale. A stable ID lets the server retrieve current authoritative data.