Checkout expired message
Likely cause: The token is invalid, belongs to another user or is older than one hour.
Check and correct: Open a fresh checkout page while signed in; do not paste tokens between accounts.
PROJECT 7 · LESSON 13 OF 16
Create durable orders with server-calculated totals, stock updates and private history.
Continue from lesson 12: Finish cart updates and understand session lifetime. 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.
Checkout turns temporary choices into durable business records. It must use server prices, protect stock, preserve historical order details and avoid creating a second order when a customer repeats the same submission.
This store uses cash on delivery. It collects a delivery address and records an amount payable on delivery; it does not collect card details or claim that payment has been received. Prices are final demo prices with delivery included. Configure your actual tax, delivery and service-area rules before accepting real customers.
SQLite is suitable for this local walkthrough, but its row-lock behavior differs from PostgreSQL. Project 8 uses PostgreSQL for deployment; run concurrent last-unit tests there before opening a store.
This store accepts cash-on-delivery orders. Placing an order records delivery details, reserves stock by decrementing it and creates a placed order; it does not charge a card or claim payment success. Demonstration prices have no extra shipping or tax calculation. Before real sales, define those policies and any cancellation, refund and fulfillment processes.
Order is the header: customer, delivery data, total, status and checkout token. OrderItem contains each purchased product plus name, unit-price and quantity snapshots. The product relationship helps staff identify inventory, but historical display uses the snapshot. Renaming a product next month must not rewrite an existing receipt.
transaction.atomic groups stock decrements, the order and its lines. If any product is unavailable or has insufficient stock, CheckoutError escapes the atomic block and the database rolls everything back. Catch the expected error outside that block to display a helpful form message. Do not catch and suppress a failure halfway through and accidentally commit partial work.
select_for_update locks rows on PostgreSQL until the transaction ends. Lock product rows in a stable ID order to reduce conflicting lock acquisition. The conditional stock update also requires sufficient stock at the database write. SQLite is suitable for the earlier learning stages but does not provide these row-lock semantics; a passing SQLite test cannot prove concurrent last-item checkout safety.
The checkout page creates a signed token containing the user ID and a random nonce. On POST, the view checks the signature, age and user association. A random or edited hidden token is rejected. A signature protects integrity; it is not encryption, and it does not replace CSRF protection.
The nonce is stored uniquely on the order. Within the transaction, lock the user row and check for an existing order with this user and token before inspecting the now-empty cart. A replay returns the existing order. A new checkout page has a new token and represents a new attempt. Redirect alone cannot handle two POSTs arriving close together.
Delivery fields come from the validated CheckoutForm. Customer identity comes from request.user. Product prices and stock come from locked database rows. The browser never supplies an accepted order total. Keep those sources distinct when reading the service call.
Order history and detail queries include user=request.user just as private tasks used owner. Knowing another order ID is not permission to view its delivery address. Clear the cart only after the transaction succeeds. An expected failure leaves choices available for correction.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
An authenticated visitor opens checkout and receives a signed per-attempt token.
POST validates delivery fields, token signature, expiry and customer association.
The service begins a transaction, locks the customer and returns an existing matching order on replay.
It locks products in stable order, validates availability and decrements stock conditionally.
It writes the order and snapshot lines, then commits all changes together.
The view clears the cart and redirects to an owner-filtered order detail page.
python manage.py migrate
python manage.py runserverThe 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.
Configure this Django project and register its applications.
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
# Local learning only. Project 8 replaces this with required production configuration.
SECRET_KEY = "development-only-edupoly-do-not-use-for-a-live-site"
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1", "testserver"]
INSTALLED_APPS = [
"django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes",
"django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles",
'shop', 'tasks', 'orders',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
TEMPLATES = [{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"], "APP_DIRS": True,
"OPTIONS": {"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
]},
}]
WSGI_APPLICATION = "config.wsgi.application"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3"}}
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
LANGUAGE_CODE = "en-us"
TIME_ZONE = "Asia/Kolkata"
USE_I18N = True
USE_TZ = True
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "tasks:list"
LOGOUT_REDIRECT_URL = "shop:home"
Route order operations through their own app.
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path
from shop.accounts import signup
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/signup/", signup, name="signup"),
path("accounts/login/", auth_views.LoginView.as_view(), name="login"),
path("accounts/logout/", auth_views.LogoutView.as_view(), name="logout"),
path("orders/", include("orders.urls")),
path("tasks/", include("tasks.urls")),
path("", include("shop.urls")),
]
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>
<a href="{% url 'orders:list' %}">My orders</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>
Create the orders application package.
Persist the order header and historical line-item snapshots.
from django.conf import settings
from django.db import models
class Order(models.Model):
class Status(models.TextChoices):
PLACED = "placed", "Placed (cash on delivery)"
SHIPPED = "shipped", "Shipped"
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
token = models.UUIDField(unique=True)
recipient = models.CharField(max_length=100)
address = models.TextField(max_length=500)
postal_code = models.CharField(max_length=20)
phone = models.CharField(max_length=30)
total = models.DecimalField(max_digits=12, decimal_places=2)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PLACED)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created_at", "-pk"]
def __str__(self):
return f"Order {self.pk}"
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE)
product = models.ForeignKey("shop.Product", on_delete=models.PROTECT)
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
@property
def line_total(self):
return self.price * self.quantity
Validate address fields and carry a signed attempt token.
from django import forms
class CheckoutForm(forms.Form):
recipient = forms.CharField(max_length=100)
address = forms.CharField(max_length=500, widget=forms.Textarea)
postal_code = forms.CharField(max_length=20)
phone = forms.CharField(max_length=30)
token = forms.CharField(widget=forms.HiddenInput)
Create an order and all stock deductions inside one transaction.
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import F
from shop.models import Product
from .models import Order, OrderItem
class CheckoutError(Exception):
pass
def place_order(*, user, token, cart, delivery):
with transaction.atomic():
# PostgreSQL serializes concurrent checkout attempts by the same user.
get_user_model().objects.select_for_update().get(pk=user.pk)
existing = Order.objects.filter(user=user, token=token).first()
if existing:
return existing
if not cart or len(cart) > 50:
raise CheckoutError("Add between 1 and 50 items before checkout.")
prepared = []
total = Decimal("0.00")
# Stable lock order reduces deadlock risk between multi-item orders.
for key, quantity in sorted(cart.items(), key=lambda pair: int(pair[0])):
if not isinstance(quantity, int) or isinstance(quantity, bool) or not 1 <= quantity <= 10:
raise CheckoutError("Invalid quantity.")
product = Product.objects.select_for_update().filter(pk=key, active=True).first()
if not product or product.stock < quantity:
raise CheckoutError("Stock changed or an item is unavailable. Review your cart.")
updated = Product.objects.filter(pk=product.pk, active=True, stock__gte=quantity).update(stock=F("stock") - quantity)
if updated != 1:
raise CheckoutError("Stock changed. Review your cart.")
prepared.append((product, quantity))
total += product.price * quantity
order = Order.objects.create(user=user, token=token, total=total, **delivery)
for product, quantity in prepared:
OrderItem.objects.create(order=order, product=product, name=product.name, price=product.price, quantity=quantity)
return order
Validate the signed request, coordinate checkout and protect order reads.
import uuid
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core import signing
from django.shortcuts import render, redirect, get_object_or_404
from shop.cart import read_cart, cart_summary
from .forms import CheckoutForm
from .models import Order
from .services import CheckoutError, place_order
SALT = "edushop-checkout"
@login_required
def checkout(request):
if request.method == "POST":
form = CheckoutForm(request.POST)
if form.is_valid():
try:
payload = signing.loads(form.cleaned_data["token"], salt=SALT, max_age=3600)
if payload["user"] != request.user.pk:
raise signing.BadSignature("Wrong account")
token = uuid.UUID(payload["nonce"])
except (signing.BadSignature, KeyError, ValueError, TypeError):
form.add_error(None, "Checkout expired. Open checkout again to review a fresh order.")
else:
delivery = {key: form.cleaned_data[key] for key in ("recipient", "address", "postal_code", "phone")}
try:
order = place_order(user=request.user, token=token, cart=read_cart(request), delivery=delivery)
except CheckoutError as error:
form.add_error(None, str(error))
else:
request.session["cart"] = {}
messages.success(request, "Order placed. Pay the stated amount on delivery; no online payment was taken.")
return redirect("orders:detail", pk=order.pk)
else:
token = signing.dumps({"user": request.user.pk, "nonce": str(uuid.uuid4())}, salt=SALT)
form = CheckoutForm(initial={"token": token})
return render(request, "orders/checkout.html", {"form": form, **cart_summary(request)})
@login_required
def order_list(request):
return render(request, "orders/list.html", {"orders": Order.objects.filter(user=request.user)})
@login_required
def order_detail(request, pk):
order = get_object_or_404(Order.objects.prefetch_related("items"), pk=pk, user=request.user)
return render(request, "orders/detail.html", {"order": order})
Name the checkout, history and detail routes.
from django.urls import path
from . import views
app_name = "orders"
urlpatterns = [
path("", views.order_list, name="list"),
path("checkout/", views.checkout, name="checkout"),
path("<int:pk>/", views.order_detail, name="detail"),
]
Show the current summary and collect delivery information.
{% extends "base.html" %}
{% block content %}<h1>Review your order</h1><p>Cash on delivery. Displayed demo prices include delivery; no separate tax or delivery fee is added. Final availability and current prices are checked on submission.</p>
{% for line in lines %}<p>{{ line.product.name|default:"Unavailable" }} × {{ line.quantity }}: ₹{{ line.total }}</p>{% empty %}<p>Your cart is empty.</p>{% endfor %}<p>Current total: ₹{{ subtotal }}</p>
{% if unavailable %}<p>Update unavailable items before ordering.</p>{% endif %}
<form method="post">{% csrf_token %}{{ form.as_p }}<button>Place cash-on-delivery order</button></form>{% endblock %}
Render only the current customer’s orders.
{% extends "base.html" %}
{% block content %}<h1>My orders</h1>{% for order in orders %}<article><a href="{% url 'orders:detail' order.pk %}">Order {{ order.pk }}</a><p>₹{{ order.total }} · {{ order.get_status_display }}</p></article>{% empty %}<p>No orders yet.</p>{% endfor %}{% endblock %}
Display saved delivery and line details without recomputing historical prices.
{% extends "base.html" %}
{% block content %}<h1>Order {{ order.pk }}</h1><p>{{ order.get_status_display }} · {{ order.created_at }}</p><p>Deliver to {{ order.recipient }}: {{ order.address }}, {{ order.postal_code }} · {{ order.phone }}</p>
{% for item in order.items.all %}<p>{{ item.name }} × {{ item.quantity }} at ₹{{ item.price }} = ₹{{ item.line_total }}</p>{% endfor %}<strong>Total payable on delivery: ₹{{ order.total }}</strong>{% endblock %}
Connect the cart to authenticated order review.
{% 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 %}
<p><a href="{% url 'orders:checkout' %}">Review checkout</a></p>{% endblock %}
Record the order schema so every checkpoint and deployment creates the same tables.
Record the order schema so every checkpoint and deployment creates the same tables.
# Generated by Django 5.2.18 on 2026-10-16 04:30
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('shop', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.UUIDField(unique=True)),
('recipient', models.CharField(max_length=100)),
('address', models.TextField(max_length=500)),
('postal_code', models.CharField(max_length=20)),
('phone', models.CharField(max_length=30)),
('total', models.DecimalField(decimal_places=2, max_digits=12)),
('status', models.CharField(choices=[('placed', 'Placed (cash on delivery)'), ('shipped', 'Shipped')], default='placed', max_length=20)),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at', '-pk'],
},
),
migrations.CreateModel(
name='OrderItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.DecimalField(decimal_places=2, max_digits=10)),
('quantity', models.PositiveIntegerField()),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.order')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='shop.product')),
],
),
]
Add two products, make the second unavailable, then submit checkout.
No order is created and the first product’s stock remains unchanged.
The first update may execute before the second product fails, but atomic rollback undoes it. A transaction protects the entire operation, not just the final insert.
A transaction must include both inventory changes and order creation. A disabled button alone does not protect against replayed submissions.
Likely cause: The token is invalid, belongs to another user or is older than one hour.
Check and correct: Open a fresh checkout page while signed in; do not paste tokens between accounts.
Likely cause: SQLite has different locking behavior from PostgreSQL.
Check and correct: Use the deployment PostgreSQL database in an isolated staging environment for the two-buyer concurrency exercise.
Add a delivery-instructions field through the form, model and migration without accepting a client-supplied total.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
A catalog price is current state. An order line is a historical agreement and must retain its original price after catalog changes.
A successful first request clears the cart. Its retry must still recover the completed order instead of failing merely because the original choices are gone.
No. Atomic gives commit-or-rollback grouping. Appropriate row locks, constraints and conditional updates are also needed for concurrent business invariants.