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.
PROJECT 6 · LESSON 12 OF 16
Update quantities, remove stale items and reason about login/logout behavior.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The visitor submits a quantity or remove form with CSRF protection.
The endpoint accepts POST and reads the cart mapping.
An update validates the requested quantity; remove deletes the selected entry.
The view assigns the result to the session and redirects.
The display reloads current product data and explains any remaining availability issues.
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.
Add validated updates and idempotent removal to the cart.
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")
Add explicit quantity-update and remove destinations.
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"),
]
Render separate update and remove forms for each line.
{% 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 %}
Send a negative quantity directly to the update endpoint.
The request does not create a negative line total, and the previous valid quantity remains.
Server validation rejects the proposed state instead of trusting the HTML number input.
Do not store an ORM Product object or Decimal directly in the JSON session. Store IDs and integer quantities, then reload product facts.
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.
Likely cause: Removal incorrectly insists on an active product lookup.
Check and correct: Remove the stored ID from the cart independently of catalog visibility.
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.
Refresh reuses the session cookie. Logout flushes that session and intentionally ends its stored state.
No. Reject the requested change and preserve the last valid state so the user can correct the input.