Skip to lesson content

PROJECT 6 · LESSON 12 OF 16

Finish cart updates and understand session lifetime

Update quantities, remove stale items and reason about login/logout behavior.

  • bound quantity forms
  • session modification
  • stale products
  • guest identity

Your workspace: edushop

Continue from lesson 11: Build a guest shopping cart. 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 cart is useful only when visitors can correct it. Updating quantities, removing unavailable items and understanding session lifetime turns a basic add button into predictable shopping behavior.

A cart quantity is a positive integer, not arbitrary text. The update view validates it and checks current stock. Removal remains possible even if a product has been archived.

Login normally rotates the session key while retaining anonymous session data. Logout flushes the session and its cart. This course does not claim to synchronize carts across devices; that requires a user-owned cart model and a merge policy.

Validate the whole requested quantity

An update form submits the desired final quantity rather than a trusted arithmetic instruction. Parse it as an integer, reject invalid or out-of-range values and keep the previous value on failure. The server must enforce the same limits even if an input has min and max attributes.

A product may have been deactivated or its stock reduced since it entered the cart. The cart should explain that situation and allow removal. Otherwise a stale item can trap the visitor. Removing by stored ID does not require the product to remain publicly active.

Keep mutation intent explicit

Add, update and remove have separate POST endpoints. Their names communicate the action, while the product ID identifies its target. The remove operation can be harmless when repeated: deleting an already-absent mapping entry should leave the cart empty rather than crash.

Redirect after each valid action so the display is based on fresh product data and the persisted session. Messages explain rejected changes without hiding the existing cart. Avoid clearing the whole cart merely because one submitted quantity is wrong.

Know exactly where the cart lives

With the database session backend, cart data is server-side but tied to a browser session identifier. It is not a customer-account cart. A different device does not automatically see it. Deleting cookies loses the browser’s reference to that session; old session data may remain until cleanup.

Django login generally preserves current session data while rotating the key, so a guest can sign in and continue checkout. Logout flushes the session, which clears this cart. This is a deliberate simple policy. Account-synchronized carts would need their own model, merge rules and conflict handling.

A normal browser refresh should preserve the cart. A server restart should also preserve a database-backed session when the database remains. Neither observation proves indefinite retention: session expiry, cookie deletion, logout and database cleanup are distinct events.

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. The visitor submits a quantity or remove form with CSRF protection.

  2. The endpoint accepts POST and reads the cart mapping.

  3. An update validates the requested quantity; remove deletes the selected entry.

  4. The view assigns the result to the session and redirects.

  5. The display reloads current product data and explains any remaining availability issues.

Compare refresh, login and logout

  1. Add an item as a guest, then refresh: it remains.
  2. Log in through the same browser: the cart remains available for checkout.
  3. Log out using the form: the session is flushed and the cart is empty. Repeat in a private window to see independent state.

3. Build it, one file at a time

  1. Replace cart_views, add the routes and update the cart template.
  2. Try zero, a fraction, and a quantity exceeding stock. The cart must not accept them.
  3. Archive a selected product in admin and return to the cart. Remove the unavailable line, then verify totals update.

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_views.py

Add validated updates and idempotent removal to the cart.

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")


@require_POST
def cart_update(request, pk):
    cart = read_cart(request)
    key = str(pk)
    form = CartQuantityForm(request.POST)
    product = Product.objects.filter(pk=pk, active=True).first()
    if key not in cart or not product or not form.is_valid():
        messages.error(request, "Choose an available item and a quantity from 1 to 10.")
    elif form.cleaned_data["quantity"] > product.stock:
        messages.error(request, "That quantity exceeds current stock.")
    else:
        cart[key] = form.cleaned_data["quantity"]
        request.session["cart"] = cart
    return redirect("shop:cart")


@require_POST
def cart_remove(request, pk):
    cart = read_cart(request)
    cart.pop(str(pk), None)
    request.session["cart"] = cart
    return redirect("shop:cart")

Read the code

  1. CartQuantityForm converts submitted text to an integer after validation. A browser min/max attribute alone is not enough.
  2. Removal uses pop with a default so removing an already absent item remains harmless. Both mutation views require POST.
  3. Every successful mutation replaces the top-level session value so Django persists it.

shop/urls.py

Add explicit quantity-update and remove destinations.

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/update/<int:pk>/", cart_views.cart_update, name="cart-update"),
    path("cart/remove/<int:pk>/", cart_views.cart_remove, name="cart-remove"),
    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. These endpoints are separate from catalog detail routes and operate only on this session’s choices.

templates/shop/cart.html

Render separate update and remove forms for each line.

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><form method="post" action="{% url 'shop:cart-update' line.id %}">{% csrf_token %}<label>Quantity <input name="quantity" type="number" min="1" max="10" value="{{ line.quantity }}"></label><button>Update</button></form><form method="post" action="{% url 'shop:cart-remove' line.id %}">{% csrf_token %}<button>Remove</button></form></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. Forms are siblings, not nested. Each has its own CSRF token and named action.
  2. A missing product can still be removed using its stored ID. The template does not hide the only recovery control.

4. Run it and check your result

  • Changing quantity updates the subtotal and survives refresh.
  • Invalid quantities and over-stock changes are rejected.
  • Removing an archived product restores a usable cart.

5. Predict, change and observe

Send a negative quantity directly to the update endpoint.

Compare your prediction with the expected result

What you should observe

The request does not create a negative line total, and the previous valid quantity remains.

Why it happens

Server validation rejects the proposed state instead of trusting the HTML number input.

6. Troubleshoot with evidence

A common mistake

Do not store an ORM Product object or Decimal directly in the JSON session. Store IDs and integer quantities, then reload product facts.

A cart is missing on another device

Likely cause: The design uses per-browser session state.

Check and correct: Test within the same session. Account cart synchronization is not implemented in this project.

An inactive product cannot be removed

Likely cause: Removal incorrectly insists on an active product lookup.

Check and correct: Remove the stored ID from the cart independently of catalog visibility.

7. Practice and explain it back

Your independent task

Explain why session-based cart persistence is not the same as saving a customer cart to their account.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why can refresh preserve the cart but logout clear it?

Refresh reuses the session cookie. Logout flushes that session and intentionally ends its stored state.

Should an invalid update empty the cart?

No. Reject the requested change and preserve the last valid state so the user can correct the input.