Skip to lesson content

PROJECT 3 · LESSON 5 OF 16

Create a database-backed product catalog

Define a Product model, create its table and manage records in Django admin.

  • ORM
  • models
  • migrations
  • admin
  • Decimal

Your workspace: edushop

Continue from lesson 4: Build a validated enquiry form. 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

Hard-coded products cannot be managed by a shop owner without editing source. A relational database gives products durable identity, typed fields and constraints, while Django’s admin supplies an immediate staff interface.

SQLite is already configured locally; no separate database server is needed yet. A model describes records in Python, while migrations describe how the database schema changes.

Django admin is a staff interface supplied by the framework. It is separate from customer account registration and should not be used as the public storefront.

A model describes records and rules

Product is a Python model class; each saved instance corresponds to a row. Fields define values such as name, slug, Decimal price, stock and active status. The primary key is a database identity. The slug is a readable public identifier and is unique so a detail URL cannot ambiguously identify two products.

Use Decimal for money because binary floating point cannot exactly represent many decimal fractions. A value such as 249.00 should remain an exact two-decimal amount during calculations. max_digits and decimal_places bound what the database can store; they do not automatically choose business policies about discounts or taxes.

Model code and database schema must move together

Editing models.py changes Python definitions. makemigrations compares model state with migration files and writes schema-change instructions. migrate applies unapplied migrations to a specific database. The database records which migrations ran. Running migrate again should not create a second copy of the same tables.

The supplied migration is part of the lesson’s complete code. If you copy it, run migrate; if you independently create the model and generate your own equivalent migration, inspect it before applying. Never delete migration history just because a command is confusing. For a disposable lab you can restart intentionally, but live databases need planned migrations and backups.

Validation has more than one layer

Model validators improve form and admin feedback, but a plain model save does not automatically call full_clean. The positive-price CheckConstraint protects the database invariant even if a different code path writes data. Unique constraints similarly protect slugs. A robust design puts important invariants where all writers must obey them.

SQLite is a convenient file database for local learning. db.sqlite3 contains application records, not source. The production project later uses PostgreSQL for persistent hosting and meaningful row locking. A local SQLite file does not automatically move into the hosted database.

Admin and repeatable seed data

Create a superuser with your own credentials and visit /admin/. Registering Product tells the admin how to expose it. list_display, filters and search improve staff navigation without creating a public editing API. A normal customer account will not receive staff privileges.

seed_products uses get_or_create with stable slugs. Running it twice should not duplicate the sample catalog or overwrite a price you edited. Seed data makes the tutorial repeatable; it is distinct from a migration, which defines database structure.

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. Django loads the installed shop app and its Product model.

  2. migrate creates the product table and constraints.

  3. seed_products inserts missing demonstration records.

  4. An authenticated superuser opens the Product admin.

  5. A validated admin save writes a row that later catalog queries can read.

Prove persistence and repeatability

  1. Run migrate, create a superuser and run seed_products.
  2. Change one price in the admin, then run seed_products again.
  3. The edited price remains and the product count does not double. Restart the server and confirm the data remains.

3. Build it, one file at a time

  1. Add the model and admin registration. If building manually without the provided migration, run python manage.py makemigrations shop to generate it. The ZIP already includes the migration shown below.
  2. Run migrate, then createsuperuser and follow its prompts. Open /admin/ and create a product.
  3. Add the seed command, run python manage.py seed_products, and rerun it to verify existing products are preserved.
Terminal
python manage.py makemigrations --check --dry-run
python manage.py migrate
python manage.py createsuperuser
python manage.py seed_products
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.

shop/models.py

Define the persistent catalog and its constraints.

shop/models.py
from decimal import Decimal
from django.core.validators import MinValueValidator
from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(Decimal("0.01"))])
    stock = models.PositiveIntegerField(default=0)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ["name", "pk"]
        constraints = [models.CheckConstraint(condition=models.Q(price__gte=Decimal("0.01")), name="positive_product_price")]

    def __str__(self):
        return self.name

Read the code

  1. DecimalField stores rupees with two decimal places, avoiding binary floating-point prices. This differs from the integer-paise Next.js example.
  2. unique=True enforces slug uniqueness in the database. The positive-price constraint complements form validation.
  3. __str__ supplies readable labels in admin. Model Meta ordering keeps list behavior predictable.

shop/migrations/__init__.py

Make migrations discoverable as a Python package.

shop/migrations/__init__.py

Read the code

  1. Commit migration files with model changes; do not commit the SQLite database.

shop/migrations/0001_initial.py

Create the Product table when migrate runs.

shop/migrations/0001_initial.py
from decimal import Decimal
from django.db import migrations, models
import django.core.validators


class Migration(migrations.Migration):
    initial = True
    dependencies = []
    operations = [migrations.CreateModel(
        name="Product",
        fields=[
            ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
            ("name", models.CharField(max_length=100)),
            ("slug", models.SlugField(unique=True)),
            ("description", models.TextField(blank=True)),
            ("price", models.DecimalField(decimal_places=2, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal("0.01"))])),
            ("stock", models.PositiveIntegerField(default=0)),
            ("active", models.BooleanField(default=True)),
        ],
        options={"ordering": ["name", "pk"], "constraints": [models.CheckConstraint(condition=models.Q(price__gte=Decimal("0.01")), name="positive_product_price")]},
    )]

Read the code

  1. This is the schema history that makemigrations would generate for this model. A migration is not a data backup.
  2. If using the provided checkpoint, apply this file with migrate; do not create a second conflicting initial migration.

shop/admin.py

Register Product with the staff administration site.

shop/admin.py
from django.contrib import admin
from .models import Product


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ["name", "price", "stock", "active"]
    list_filter = ["active"]
    search_fields = ["name", "slug"]
    prepopulated_fields = {"slug": ("name",)}

Read the code

  1. ModelAdmin customizes list columns, filters and searches. prepopulated_fields suggests a slug in the browser; the database still enforces uniqueness.
  2. Only authenticated staff with appropriate permissions can use admin. Customer signup later does not create staff accounts.

shop/management/__init__.py

Enable custom management-command discovery.

shop/management/__init__.py

Read the code

  1. This package groups commands that run with Django settings loaded.

shop/management/commands/__init__.py

Mark the commands directory as a package.

shop/management/commands/__init__.py

Read the code

  1. The seed_products filename becomes the management command name.

shop/management/commands/seed_products.py

Create three starter records without resetting later edits.

shop/management/commands/seed_products.py
from decimal import Decimal
from django.core.management.base import BaseCommand
from shop.models import Product


class Command(BaseCommand):
    help = "Create learning products without overwriting existing records"

    def handle(self, *args, **options):
        for slug, name, price in [("notebook", "Learning notebook", "249.00"), ("desk-lamp", "Desk lamp", "899.00"), ("pen-set", "Pen set", "99.00")]:
            Product.objects.get_or_create(slug=slug, defaults={"name": name, "price": Decimal(price), "stock": 20, "description": "A useful addition to your learning workspace."})
        self.stdout.write(self.style.SUCCESS("Learning products are ready."))

Read the code

  1. get_or_create matches by unique slug and applies defaults only for a new record.
  2. This command is repeatable. Running it again does not refill stock or overwrite an edited price.

4. Run it and check your result

  • migrate creates the Product table and admin can save a product.
  • Running seed_products twice does not duplicate or overwrite records.

5. Predict, change and observe

Try saving a second product with the same slug through admin.

Compare your prediction with the expected result

What you should observe

The form reports a uniqueness problem rather than creating an ambiguous detail address.

Why it happens

The unique field participates in validation and has database enforcement. A pretty URL still needs a stable unique lookup.

6. Troubleshoot with evidence

A common mistake

If you see no such table, apply migrations to the database used by this environment. Do not delete migration history as a first response.

No such table: shop_product

Likely cause: The current database has not received the migration.

Check and correct: Run python manage.py showmigrations and python manage.py migrate using the same settings as the server.

Product is missing from admin

Likely cause: The app or admin registration is absent.

Check and correct: Check INSTALLED_APPS, shop/admin.py and that the logged-in staff user has permissions.

7. Practice and explain it back

Your independent task

Add a category field and create/apply its migration. Explain why a Python-only change is insufficient.

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

Does makemigrations insert sample products?

No. It writes schema history. The seed management command inserts data, and migrate applies schema changes.

Why keep both a validator and a constraint?

The validator gives a readable form error. The database constraint protects the invariant when code bypasses that form.