Skip to lesson content

PROJECT 6 · LESSON 11 OF 16

Build a guest shopping cart

Persist product selections in a Django session and calculate totals from database prices.

  • sessions
  • Decimal totals
  • POST actions
  • cart identity

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Store choices, then derive presentation

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.

A cart is not a stock reservation

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.

Write sessions in a way Django notices

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. A visitor submits the product add form.

  2. The view verifies POST and retrieves an active product.

  3. The helper reads and validates the session cart.

  4. The updated ID-to-quantity map is assigned back to the session.

  5. A cart GET loads current products and calculates Decimal line totals and a total.

Calculate a two-item line

  1. For a product priced at ₹249.00, add quantity two.
  2. The session stores its ID and 2, not ₹498.00.
  3. The cart view retrieves ₹249.00 from the product and derives ₹498.00 for display.

3. Build it, one file at a time

  1. Add cart.py and the cart views, then update the product detail page with an Add button.
  2. Add two notebooks and one pen set. The subtotal should be ₹597.00.
  3. Refresh the page and close/reopen a tab. The session can persist while the same browser retains its cookie.

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.

shop/cart.py

Interpret session selections and derive a current catalog summary.

shop/cart.py
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}

Read the code

  1. Validate the session structure before using it. Keys are string IDs because session serialization uses JSON.
  2. Product queries reload authoritative prices. Decimal arithmetic computes each line and subtotal without storing a second total.
  3. Unavailable products are flagged rather than silently accepted as free items. Checkout later rejects them.

shop/forms.py

Add an integer quantity form alongside the enquiry form.

shop/forms.py
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)

Read the code

  1. The quantity limits are server rules. The next lesson uses this form for updates.

shop/cart_views.py

Allow guest users to add available products through POST.

shop/cart_views.py
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")

Read the code

  1. require_POST rejects GET mutations. CSRF middleware additionally requires a valid form token.
  2. Assigning the entire updated dict back to request.session marks the session modified. Nested mutation alone may not do so.
  3. Stock and quantity limits provide useful feedback, but checkout must recheck them because another buyer can order meanwhile.

shop/urls.py

Expose the cart page and its add action.

shop/urls.py
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"),
]

Read the code

  1. GET /cart/ displays data; POST /cart/add/id/ changes the session. They have distinct responsibilities.

templates/base.html

Provide the shared HTML document, navigation and content slots.

templates/base.html
{% 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>

Read the code

  1. extends in a child template reuses this document; block content is where that child supplies its page.
  2. url resolves named routes and static builds the asset URL. These are server-side template tags, not browser JavaScript.
  3. Messages report the outcome after a redirect. Once authentication is added, logout uses a CSRF-protected POST form.

templates/shop/product_detail.html

Add a CSRF-protected action to the product page.

templates/shop/product_detail.html
{% 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 %}

Read the code

  1. The product primary key identifies the requested item. The view ignores any caller-supplied price.
  2. The button is hidden for zero stock, but the server still checks availability because a visitor can submit directly.

templates/shop/cart.html

Display the summary supplied by the cart service.

templates/shop/cart.html
{% 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 %}

Read the code

  1. Each row combines a product with its selected quantity. An absent product has an explicit fallback label.
  2. The template displays subtotal; it does not reconstruct arithmetic from formatted strings.

4. Run it and check your result

  • Two notebooks and one pen set display ₹597.00.
  • Refresh preserves the cart in the same session; a GET to the add endpoint returns 405.

5. Predict, change and observe

Change a product price in admin after adding it to a cart.

Compare your prediction with the expected result

What you should observe

The next cart display uses the new price.

Why it happens

The session stores choices. The database remains the authority for the current catalog price; order snapshots arrive later.

6. Troubleshoot with evidence

A common mistake

Never save a browser-submitted price as the authoritative order price.

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"].

Decimal cannot be JSON serialized

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.

7. Practice and explain it back

Your independent task

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.

Does adding reserve stock?

No. It is a temporary choice. The final checkout transaction validates and changes stock.

Why not store a complete Product object in the session?

It is not a simple serializable value and would become stale. A stable ID lets the server retrieve current authoritative data.