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.
PROJECT 3 · LESSON 5 OF 16
Define a Product model, create its table and manage records in Django admin.
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.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
Django loads the installed shop app and its Product model.
migrate creates the product table and constraints.
seed_products inserts missing demonstration records.
An authenticated superuser opens the Product admin.
A validated admin save writes a row that later catalog queries can read.
python manage.py makemigrations --check --dry-run
python manage.py migrate
python manage.py createsuperuser
python manage.py seed_products
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.
Define the persistent catalog and its constraints.
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
Make migrations discoverable as a Python package.
Create the Product table when migrate runs.
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")]},
)]
Register Product with the staff administration site.
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",)}
Enable custom management-command discovery.
Mark the commands directory as a package.
Create three starter records without resetting later edits.
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."))
Try saving a second product with the same slug through admin.
The form reports a uniqueness problem rather than creating an ambiguous detail address.
The unique field participates in validation and has database enforcement. A pretty URL still needs a stable unique lookup.
If you see no such table, apply migrations to the database used by this environment. Do not delete migration history as a first response.
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.
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.
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.
No. It writes schema history. The seed management command inserts data, and migrate applies schema changes.
The validator gives a readable form error. The database constraint protects the invariant when code bypasses that form.