Project: Library Catalogue
In this project you will build a complete catalogue for a small community lending library in Kochi. Members search the books page by page and see how many copies are on the shelf. Ananya and Rohan see only their own borrowed books. Meera, the librarian, issues and takes back books at a desk screen, and the API refuses to lend a copy that is not there, even when two requests arrive at the same moment.
What you should know first: the whole course, especially ViewSets, Routers & Permissions, Login, Protected Routes & Sessions, Testing Django + React, Security Checklist and Deploying Django + React. Everything below ran on Django 6.1.3, Django REST Framework 3.18.3, PostgreSQL 18.6, React 19.3.1, React Router 8.5.1 and Vite 8.3.8.
What you will build
| Who | Screen (React) | API (Django) |
|---|---|---|
| Anyone | / catalogue with search and pages | GET /api/books/?search=&page= |
| Anyone | /books/9 one book and its availability | GET /api/books/9/ |
| Member | /my-books books at home and due dates | GET /api/loans/?open=true (own loans only) |
| Staff | /desk issue form and books out now | POST /api/loans/, POST /api/loans/<id>/return/ |
The library's rules: a loan lasts 14 days, a member may hold at most 3 books, never two copies of the same book, and a book with no copy on the shelf cannot be issued. Think of the old card register at the counter: the rules live with the librarian, not with the person asking. Here the librarian is Django.
Step 1: start from BookShelf's skeleton
A real team reuses what already works. Create library/backend and library/frontend, then copy from BookShelf:
library/
├── backend/
│ ├── accounts/ copied: User, login, logout, me, CSRF views and their tests
│ ├── catalogue/ new: Book, Loan, serializers, views, permissions, tests
│ ├── config/ copied: settings (security, throttles, PostgreSQL, WhiteNoise)
│ ├── .env new secret key
│ ├── manage.py, pytest.ini, requirements.txt
└── frontend/
└── src/
├── api/client.js, hooks/useApi.js, utils/errors.js copied
├── auth/ (AuthProvider, RequireAuth, auth-context) copied
├── auth/RequireStaff.jsx, utils/dates.js new
└── pages/ CataloguePage, BookPage, MyLoansPage, DeskPage newCreate the app with django-admin startapp catalogue, then in config/settings.py replace "books" with "catalogue" in INSTALLED_APPS and rename the cache table to library_cache. In config/urls.py, include catalogue.urls under api/. Generate a fresh DJANGO_SECRET_KEY for .env; never reuse BookShelf's.
Step 2: models with a database-level rule
catalogue/models.py:
from django.conf import settings
from django.db import models
from django.db.models import Q
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=120)
isbn = models.CharField("ISBN", max_length=13, unique=True)
subject = models.CharField(max_length=60, blank=True)
copies = models.PositiveSmallIntegerField(default=1)
class Meta:
ordering = ["title"]
def __str__(self):
return self.title
class Loan(models.Model):
book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name="loans")
member = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="loans")
issued_on = models.DateField(auto_now_add=True)
due_on = models.DateField()
returned_on = models.DateField(null=True, blank=True)
class Meta:
ordering = ["due_on"]
constraints = [
# A member may hold only one copy of the same book at a time
models.UniqueConstraint(
fields=["book", "member"],
condition=Q(returned_on__isnull=True),
name="one_open_loan_per_member_per_book",
),
]A loan is never deleted; returning sets returned_on, so the history stays. That is also why both foreign keys use PROTECT. The constraint has a condition, which makes it a partial unique index: it applies only to open loans, so Ananya may borrow Godaan again next month. PostgreSQL and SQLite both support it.
python manage.py makemigrations catalogueMigrations for 'catalogue':
catalogue\migrations\0001_initial.py
+ Create model Book
+ Create model LoanRegister both models in catalogue/admin.py, so Meera can add books there. A fixture, catalogue/fixtures/library_books.json, loads twelve books (with made-up ISBNs such as 9780000000001): Installed 12 object(s) from 1 fixture(s).
Step 3: the issue rule, safe under pressure
Two serializers matter. BookSerializer lists the fields plus a read-only available, and checks that an ISBN has 10 or 13 digits. LoanSerializer is read-only and adds book_title, member_name and is_overdue. Issuing a book has its own serializer in catalogue/serializers.py:
LOAN_DAYS = 14
MAX_OPEN_LOANS = 3
class IssueSerializer(serializers.Serializer):
"""Staff issue a book: POST {"book": 3, "member": "ananya"}."""
book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all())
member = serializers.SlugRelatedField(slug_field="username", queryset=User.objects.filter(is_active=True))
def validate(self, attrs):
open_loans = attrs["member"].loans.filter(returned_on__isnull=True)
if open_loans.count() >= MAX_OPEN_LOANS:
raise serializers.ValidationError(f"A member may hold at most {MAX_OPEN_LOANS} books.")
if open_loans.filter(book=attrs["book"]).exists():
raise serializers.ValidationError("This member already has this book.")
return attrs
def create(self, validated_data):
with transaction.atomic():
# Lock the book row: two desks cannot lend the last copy at once
book = Book.objects.select_for_update().get(pk=validated_data["book"].pk)
on_loan = book.loans.filter(returned_on__isnull=True).count()
if on_loan >= book.copies:
raise serializers.ValidationError({"book": ["No copies are available right now."]})
return Loan.objects.create(
book=book,
member=validated_data["member"],
due_on=timezone.localdate() + timedelta(days=LOAN_DAYS),
)The copy check needs care. Imagine two librarians clicking "Issue" for the last copy of Chemmeen in the same second. Both count zero open loans, both create a loan, and the shelf now owes a book it does not have. This is a race condition. select_for_update() inside transaction.atomic() locks the book's row in PostgreSQL until the transaction ends, so the second request waits, then counts the first loan. SQLite ignores the lock but allows only one writer at a time anyway, which is one more reason production uses PostgreSQL. A ValidationError raised inside create() still becomes a normal 400 answer.
Step 4: views with pagination, search and private lists
catalogue/permissions.py keeps IsStaffOrReadOnly from BookShelf and adds one class:
class IsStaffForWrites(permissions.BasePermission):
"""Logged-in members may read (their own) loans. Only staff issue and return."""
def has_permission(self, request, view):
if not request.user.is_authenticated:
return False
return request.method in permissions.SAFE_METHODS or request.user.is_staffcatalogue/views.py:
class CataloguePages(PageNumberPagination):
page_size = 10 # ?page=2 for the next ten
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
permission_classes = [IsStaffOrReadOnly]
pagination_class = CataloguePages
filter_backends = [filters.SearchFilter]
search_fields = ["title", "author", "isbn", "subject"] # ?search=premchand
def get_queryset(self):
open_loans = Count("loans", filter=Q(loans__returned_on__isnull=True))
return Book.objects.annotate(available=F("copies") - open_loans).order_by("title")
class LoanViewSet(mixins.CreateModelMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = LoanSerializer
permission_classes = [IsStaffForWrites]
def get_queryset(self):
loans = Loan.objects.select_related("book", "member")
if not self.request.user.is_staff:
loans = loans.filter(member=self.request.user) # members see only their own
if self.request.query_params.get("open") == "true":
loans = loans.filter(returned_on__isnull=True)
return loans
def create(self, request):
issue = IssueSerializer(data=request.data)
issue.is_valid(raise_exception=True)
loan = issue.save()
return Response(LoanSerializer(loan).data, status=status.HTTP_201_CREATED)
@action(detail=True, methods=["post"], url_path="return")
def return_book(self, request, pk=None):
"""POST /api/loans/<id>/return/: the book is back on the shelf. Staff only."""
loan = self.get_object()
if loan.returned_on is not None:
raise ValidationError({"detail": "This loan was already closed."})
loan.returned_on = timezone.localdate()
loan.save(update_fields=["returned_on"])
return Response(LoanSerializer(loan).data)- Pagination changes the contract. The book list now answers
{"count", "next", "previous", "results"}instead of a plain array. Decide this before React is written, as BookShelf's first lesson said about contracts. SearchFilteris DRF's built-in version of theQsearch you wrote by hand in BookShelf. It still uses the ORM, so it is safe from SQL injection.availableis one query. The database subtracts open loans from copies for all ten books at once.- Private rows are filtered in
get_queryset(). Object permissions never filter lists, as the viewsets lesson warned; this line is the real privacy rule. - No update or delete. The mixins give list, retrieve and create only.
returnis a Python keyword, so the method isreturn_bookandurl_pathsets the URL.
The router registers books and loans with basename values, exactly like BookShelf.
Step 5: try the API
We migrated into a fresh PostgreSQL database owned by a library role, loaded the fixture, created Meera as staff and two members, and logged in with curl cookie jars as in the auth lesson. A search for narayan, then page 2 (results shortened):
{"count":3,"next":null,"previous":null,"results":[{"id":2,"title":"Malgudi Days","author":"R. K. Narayan","isbn":"9780000000002","subject":"Short stories","copies":3,"available":3}, ...]}
{"count":12,"next":null,"previous":"http://127.0.0.1:8042/api/books/","results":[{"id":8,"title":"Train to Pakistan", ...},{"id":3,"title":"Wings of Fire", ...}]}Meera then issued Chemmeen (one copy) to Ananya, the same book to Rohan, two more books to Ananya, a fourth, and finally Ananya tried to issue a book to herself:
{"id":1,"book":5,"book_title":"Chemmeen","member_name":"ananya","issued_on":"2026-11-17","due_on":"2026-12-01","returned_on":null,"is_overdue":false}
{"book":["No copies are available right now."]}
{"id":2,"book":1,"book_title":"Godaan", ...}
{"id":3,"book":7,"book_title":"The Guide", ...}
{"non_field_errors":["A member may hold at most 3 books."]}
{"detail":"You do not have permission to perform this action."}Finally we sent two issue requests for the single copy of Train to Pakistan at the same time, for Rohan and for Meera. One got 201 and the other {"book":["No copies are available right now."]}, and the book showed "available":0.
Step 6: tests for every rule
catalogue/tests.py uses pytest fixtures for a logged-in desk client and a member. One test per rule:
def test_last_copy_cannot_be_issued_twice(desk, ananya):
book = make_book(copies=1)
User.objects.create_user("rohan", password="x")
issue(desk, book)
response = issue(desk, book, member="rohan")
assert response.status_code == 400
assert response.data == {"book": ["No copies are available right now."]}
def test_members_see_only_their_own_loans(desk, ananya):
User.objects.create_user("rohan", password="x")
issue(desk, make_book("Godaan"))
issue(desk, make_book("Nirmala"), member="rohan")
client = APIClient()
client.force_authenticate(ananya)
titles = [loan["book_title"] for loan in client.get("/api/loans/").data]
assert titles == ["Godaan"]The others check that issuing lowers available, the three-book limit, that members get 403 when issuing, that returning frees the copy and cannot happen twice, and that twelve books give a second page of two. With BookShelf's copied login tests:
accounts\tests.py .... [ 36%] catalogue\tests.py ....... [100%] ============================= 11 passed in 18.78s =============================
Step 7: the React screens
Routes in App.jsx: the catalogue at the index, books/:bookId, login, then my-books and account inside RequireAuth, and desk inside a new RequireStaff guard. That guard is RequireAuth plus one line: if !user.is_staff, show "Only library staff can open the desk." The header shows "My books" to members and "Desk" to staff. Django still checks every request.
The catalogue keeps search and page number in the URL, so a link to page 2 of a search can be shared:
export default function CataloguePage() {
const [params, setParams] = useSearchParams();
const search = params.get("search") ?? "";
const page = Number(params.get("page") ?? "1") || 1;
const apiParams = new URLSearchParams({ page: String(page) });
if (search.trim()) apiParams.set("search", search.trim());
const books = useApi(`/books/?${apiParams}`);
function goTo(nextPage) {
const next = new URLSearchParams(params);
next.set("page", String(nextPage));
setParams(next);
}
function handleSearch(event) {
const value = event.target.value;
setParams(value ? { search: value } : {}, { replace: true }); // a new search starts at page 1
}
// ... render the count, the list with "2 of 3 on the shelf", and Previous/Next buttons
// disabled when data.previous or data.next is null
}Use next and previous from the API to enable the buttons, rather than guessing from the count. Here is the same pager logic with fake data:
import { useState } from "react";
import { createRoot } from "react-dom/client";
const titles = ["Chemmeen", "Gitanjali", "Godaan", "Ignited Minds", "Malgudi Days", "Nirmala", "Swami and Friends",
"The Discovery of India", "The Guide", "The Story of My Experiments with Truth", "Train to Pakistan", "Wings of Fire"];
// Behaves like DRF's PageNumberPagination with page_size = 5
function fakeApi(page) {
const results = titles.slice((page - 1) * 5, page * 5);
return { count: titles.length, previous: page > 1 ? `?page=${page - 1}` : null, next: page * 5 < titles.length ? `?page=${page + 1}` : null, results };
}
function Pager() {
const [page, setPage] = useState(1);
const data = fakeApi(page);
return (
<main>
<p>{data.count} books</p>
<ol start={(page - 1) * 5 + 1}>{data.results.map((t) => <li key={t}>{t}</li>)}</ol>
<button type="button" disabled={!data.previous} onClick={() => setPage(page - 1)}>Previous</button>{" "}
Page {page} of {Math.ceil(data.count / 5)}{" "}
<button type="button" disabled={!data.next} onClick={() => setPage(page + 1)}>Next</button>
</main>
);
}
createRoot(document.getElementById("root")).render(<Pager />);The desk page reuses the BookShelf form pattern: controlled inputs, splitErrors(error, ["book", "member"]), FieldError under each box and a role="alert" box for whole-form errors. After a successful issue or return it calls loans.reload(). utils/dates.js turns Django's "2026-12-01" into "Due 1 Dec 2026" with Intl.DateTimeFormat("en-IN"), and has its own Vitest test.
We drove the real app in headless Chrome through the Vite proxy. Logged in as Meera on /desk, issuing book 9 to Rohan and then book 8 (no copy left) to Ananya showed:
Issued Ignited Minds to rohan. Due 1 Dec 2026. ... No copies are available right now.
The second message appeared under the "Book number" box, because Django named the book field. As Ananya, /my-books showed only The Guide: Due 1 Dec 2026, and /desk showed "Only library staff can open the desk." npm run lint found nothing, and Vitest passed 5 tests.
Step 8: ship it
Nothing new is needed: follow Deploying Django + React with library in place of bookshelf. Run createcachetable after migrate, keep client_max_body_size at the default (there are no uploads), and run check --deploy with production settings. npm run build produced a 269 KB JavaScript bundle (85 KB gzipped).
Interview questions
1. What is a race condition, and how did this project prevent one?
Two requests read the same state and both act on it, so a rule breaks: here, both issue the last copy. Locking the book row with select_for_update() inside a transaction makes the second request wait until the first commits, then see the new loan.
2. Why filter loans in get_queryset() instead of using an object permission?
Object permissions run only when one object is loaded, never for lists. Filtering the queryset by request.user means a member can neither list nor fetch another member's loans; the other ids simply return 404.
3. What does a partial unique constraint do?
It enforces uniqueness only for rows that match a condition. Here a member can have only one open loan per book, but closed loans of the same book are allowed, so the history is kept.
4. How does pagination change the API contract for React?
The list becomes an object with count, next, previous and results. React must read results for the rows and use next and previous to enable buttons, so both sides must agree on it early.
Key points
- Reuse what works: settings, login,
apiFetch, guards and form helpers came from BookShelf. - Put business rules in serializers and the database: limits, a partial unique constraint and a locked row.
select_for_update()intransaction.atomic()stops two requests from lending the last copy.- Paginate and search with DRF's built-in classes; keep page and search in React's URL.
- Filter private rows in
get_queryset(); staff-only actions need both a permission class and a React guard. - Test every rule through the API, then deploy exactly as BookShelf.
Exercise
Meera wants to see late books. Add ?overdue=true to GET /api/loans/ so it returns only open loans whose due date has passed. Write a pytest test that issues two books, moves one loan's due_on three days into the past, and checks that only that book is listed, with "is_overdue": true.
Show solution
# catalogue/views.py, in LoanViewSet.get_queryset(), before "return loans"
if self.request.query_params.get("overdue") == "true":
loans = loans.filter(returned_on__isnull=True, due_on__lt=timezone.localdate())# catalogue/tests.py (also import timedelta, timezone and Loan)
def test_overdue_filter_lists_only_late_open_loans(desk, ananya):
late = issue(desk, make_book("Godaan")).data["id"]
issue(desk, make_book("Nirmala"))
Loan.objects.filter(pk=late).update(due_on=timezone.localdate() - timedelta(days=3))
rows = desk.get("/api/loans/?overdue=true").data
assert [row["book_title"] for row in rows] == ["Godaan"]
assert rows[0]["is_overdue"] is TrueThe filter sits after the member filter, so a member asking for ?overdue=true still sees only their own late books. update() changes the date directly in the database, which is the quickest way to make a test loan late. The test passed in our project.
Quick Quiz
1. Why does the project lock the book row before counting open loans?
Without the lock, both requests can count zero loans and both succeed.
2. A member calls GET /api/loans/. Which loans come back?
Members may read loans, but the queryset limits them to their own.
3. What shape does GET /api/books/?page=2 return?
DRF's PageNumberPagination wraps the rows with paging details.
4. Why is returned_on set instead of deleting a returned loan?
Closed loans stay as history, and the condition lets a member borrow the same book again later.
Learn Django + React with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
