Skip to lesson content

PROJECT 7 · LESSON 13 OF 16

Build cash-on-delivery checkout and order history

Create durable orders with server-calculated totals, stock updates and private history.

  • transactions
  • idempotency
  • order snapshots
  • delivery forms

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Define the complete order contract

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.

A transaction makes a multi-record change indivisible

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.

Duplicate submission is a different problem from validation

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.

Trust boundaries remain visible

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.

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. An authenticated visitor opens checkout and receives a signed per-attempt token.

  2. POST validates delivery fields, token signature, expiry and customer association.

  3. The service begins a transaction, locks the customer and returns an existing matching order on replay.

  4. It locks products in stable order, validates availability and decrements stock conditionally.

  5. It writes the order and snapshot lines, then commits all changes together.

  6. The view clears the cart and redirects to an owner-filtered order detail page.

Buy the same notebook once

  1. A notebook costs ₹249.00 and has stock 3. Submit quantity 2 with token T.
  2. The committed result is one ₹498.00 order and stock 1. Change the catalog price afterward; this order still shows ₹249.00 per unit.
  3. Replay token T. The service returns the existing order; stock stays 1. Try a new checkout for quantity 2 and it fails without a partial order.

3. Build it, one file at a time

  1. Add the orders app, settings registration and routes. Add the models, form, service, views and templates. The completed checkpoint includes the generated initial orders migration; when typing from scratch run makemigrations orders before migrate.
  2. Sign in, add products, open /orders/checkout/, review the current price and complete delivery details. Submit and inspect your order history.
  3. Refresh the resulting order detail page. Then change a product’s name or price in admin and confirm the old order retains its saved values.
  4. Test an out-of-stock line and confirm no partial order or partial stock deduction remains. The supplied automated tests in the next lesson verify this.
Terminal
python manage.py migrate
python manage.py runserver

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.

config/settings.py

Configure this Django project and register its applications.

config/settings.py
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"

Read the code

  1. INSTALLED_APPS enables model discovery, templates and management features. Adding a directory alone does not register an app.
  2. MIDDLEWARE wraps requests in order: sessions precede authentication, and CSRF protects unsafe form submissions.
  3. DIRS finds the shared templates folder; APP_DIRS also searches installed app templates. SQLite stores local records in db.sqlite3.
  4. This development configuration is intentionally replaced in Project 8. Its fixed local key and DEBUG=True must never be deployed.

config/urls.py

Route order operations through their own app.

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

Read the code

  1. The orders namespace separates customer history from staff admin. checkout is listed before the integer detail route.

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

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.

orders/__init__.py

Create the orders application package.

orders/__init__.py

Read the code

  1. Orders coordinate catalog inventory and customer identity without moving all logic into a template.

orders/models.py

Persist the order header and historical line-item snapshots.

orders/models.py
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

Read the code

  1. Order links to the authenticated user and records delivery details and total. The unique token identifies one checkout attempt.
  2. OrderItem stores the name and unit price at purchase time. Reading current Product prices later would rewrite history.
  3. PROTECT prevents deleting referenced users or products accidentally. Customer requests cannot set status or ownership.

orders/forms.py

Validate address fields and carry a signed attempt token.

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

Read the code

  1. The form accepts only delivery input and the hidden token. It accepts no user ID, price, total or fulfillment status.
  2. The token is signed and checked in the view. Hidden fields are not inherently trustworthy.

orders/services.py

Create an order and all stock deductions inside one transaction.

orders/services.py
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

Read the code

  1. The user lock serializes same-user checkouts on PostgreSQL. An existing token returns its already-created order before inspecting a now-cleared cart.
  2. Product rows are processed in stable ID order. Current database prices determine totals; conditional F updates require enough stock at write time.
  3. Raising CheckoutError aborts the transaction, including deductions already made for earlier lines. No email or external payment is performed inside the retry-sensitive database operation.

orders/views.py

Validate the signed request, coordinate checkout and protect order reads.

orders/views.py
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})

Read the code

  1. login_required supplies the authenticated request context. signing.loads enforces an hour limit and the payload must match the current user.
  2. On a valid POST, the service returns a durable order, the cart is cleared and redirect implements Post/Redirect/Get. Replaying the same valid token returns the original order.
  3. List and detail queries filter on request.user. A signed-in customer cannot obtain another customer’s order by guessing its ID.

orders/urls.py

Name the checkout, history and detail routes.

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

Read the code

  1. <int:pk> validates URL shape; owner filtering remains the view’s responsibility.

templates/orders/checkout.html

Show the current summary and collect delivery information.

templates/orders/checkout.html
{% 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 %}

Read the code

  1. The view supplies current product prices; the service checks them again during submission.
  2. Error messages appear on the bound form. A real price-confirmation workflow may add versioned quotes; this demo explicitly accepts current server prices.

templates/orders/list.html

Render only the current customer’s orders.

templates/orders/list.html
{% 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 %}

Read the code

  1. The view performs the ownership filter before the records enter the template.

templates/orders/detail.html

Display saved delivery and line details without recomputing historical prices.

templates/orders/detail.html
{% 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 %}

Read the code

  1. order.items uses the related_name from the foreign key. prefetch_related in the view avoids an extra query per displayed relation.
  2. Personal delivery information is shown only after the owner-filtered lookup succeeds.

templates/shop/cart.html

Connect the cart to authenticated order review.

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 %}
<p><a href="{% url 'orders:checkout' %}">Review checkout</a></p>{% endblock %}

Read the code

  1. Guests can browse and use the cart, but checkout redirects them to login before accepting an order.

orders/migrations/__init__.py

Record the order schema so every checkpoint and deployment creates the same tables.

orders/migrations/__init__.py

Read the code

  1. The migration depends on the product schema and the configured user model.
  2. Run migrate to apply this versioned schema. Commit migrations with the model changes; do not regenerate them on each deployment.

orders/migrations/0001_initial.py

Record the order schema so every checkpoint and deployment creates the same tables.

orders/migrations/0001_initial.py
# 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')),
            ],
        ),
    ]

Read the code

  1. The migration depends on the product schema and the configured user model.
  2. Run migrate to apply this versioned schema. Commit migrations with the model changes; do not regenerate them on each deployment.

4. Run it and check your result

  • An authenticated customer can place an order and see only their own history.
  • Successful ordering deducts stock and preserves historical names/prices.
  • Unavailable stock aborts the whole operation.

5. Predict, change and observe

Add two products, make the second unavailable, then submit checkout.

Compare your prediction with the expected result

What you should observe

No order is created and the first product’s stock remains unchanged.

Why it happens

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.

6. Troubleshoot with evidence

A common mistake

A transaction must include both inventory changes and order creation. A disabled button alone does not protect against replayed submissions.

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.

Database locked during concurrent local tests

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.

7. Practice and explain it back

Your independent task

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.

Why store unit price on OrderItem?

A catalog price is current state. An order line is a historical agreement and must retain its original price after catalog changes.

Why check the existing token before the cart?

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.

Does atomic prevent every race by itself?

No. Atomic gives commit-or-rollback grouping. Appropriate row locks, constraints and conditional updates are also needed for concurrent business invariants.