Tasks table missing
Likely cause: The new app migration has not been applied.
Check and correct: Check installed apps, run showmigrations tasks, then migrate.
PROJECT 4 · LESSON 7 OF 16
Add a second Django app and use a ModelForm to validate and save records.
Continue from lesson 6: Build product pages, search and pagination. 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.
A task manager isolates database writing from ecommerce complexity. Before orders and stock, learn one dependable create-and-list cycle: validate a title, save one record, redirect and read it back.
The tasks app lives inside the same Django project as shop. It shares settings, database and base template but owns its model, forms and routes. This demonstrates composition without a second server.
These first CRUD lessons intentionally show shared local tasks. Do not publish this intermediate checkpoint with personal data. Project 5 protects both reads and writes.
CRUD means create, read, update and delete. A Task contains a title, completion flag and creation timestamp. The owner relationship is prepared now but remains nullable during the local shared-task project. Authentication later changes the access rules; do not put this deliberately shared lab on the public internet.
The tasks app groups its model, forms, views, URLs and templates. Add it to INSTALLED_APPS so Django discovers its model and templates. Include its URLs at /tasks/ so it coexists with the storefront. App boundaries organize code inside one project and database; they do not require separate servers.
TaskForm declares the fields a visitor may submit. A whitelist is important: future model fields should not automatically become editable. If an owner field exists, a visitor must not choose another owner through a hidden input. Later the server will assign request.user after validation.
A valid ModelForm can create a model instance with save. Before saving, is_valid checks field-level and model-related form constraints. clean_title normalizes whitespace and rejects an empty result. Normalization prevents apparently different strings such as a title padded with spaces from being stored unnecessarily.
After a successful POST, redirect to the task list. The list performs a new database read. This makes the outcome visible and avoids ordinary browser refresh resubmission. On invalid input, render the same bound form so errors and entered values remain together.
Do not confuse a Python object with a persisted row. Constructing Task(title=...) creates an in-memory instance. save writes it. ModelForm.save combines these steps after validation. In the next project, commit=False will intentionally pause before writing so the server can attach the owner.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
GET /tasks/ queries tasks and renders the current list.
GET create displays an unbound TaskForm.
POST create binds and validates submitted fields.
A valid form saves one task; an invalid form returns errors without saving.
A redirect performs a fresh list GET, showing the stored record.
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',
]
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"
Dispatch incoming paths to the correct application.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.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>
</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 a separate Python app for task features.
Define persistent task data and a future ownership relationship.
from django.conf import settings
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=120)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
# Null only for the early shared-data lab. Later views require an owner.
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
class Meta:
ordering = ["-created_at", "-pk"]
def __str__(self):
return self.title
Enable task migrations.
Create the task table after the auth user table exists.
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
operations = [migrations.CreateModel(name="Task", fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("title", models.CharField(max_length=120)),
("completed", models.BooleanField(default=False)),
("created_at", models.DateTimeField(auto_now_add=True)),
("owner", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
], options={"ordering": ["-created_at", "-pk"]})]
Generate a form for only the user-editable task fields.
from django import forms
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ["title", "completed"]
def clean_title(self):
title = self.cleaned_data["title"].strip()
if not title:
raise forms.ValidationError("Enter a meaningful title.")
return title
Read all shared lab tasks and save a valid creation form.
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from .forms import TaskForm
from .models import Task
def task_list(request):
return render(request, "tasks/list.html", {"tasks": Task.objects.all()})
def task_create(request):
form = TaskForm(request.POST if request.method == "POST" else None)
if request.method == "POST" and form.is_valid():
form.save()
messages.success(request, "Task created.")
return redirect("tasks:list")
return render(request, "tasks/form.html", {"form": form, "heading": "Create task"})
Give the app its own namespaced list and create routes.
from django.urls import path
from . import views
app_name = "tasks"
urlpatterns = [
path("", views.task_list, name="list"),
path("new/", views.task_create, name="create"),
]
Render persistent task rows or an empty state.
{% extends "base.html" %}
{% block content %}<h1>Tasks</h1><a href="{% url 'tasks:create' %}">Create task</a>
{% for task in tasks %}<article><h2>{{ task.title }}</h2><p>{{ task.completed|yesno:"Completed,Open" }}</p></article>{% empty %}<p>No tasks yet.</p>{% endfor %}{% endblock %}
Use one form template for create now and edit later.
{% extends "base.html" %}
{% block content %}<h1>{{ heading }}</h1><form method="post">{% csrf_token %}{{ form.as_p }}<button>Save task</button></form><a href="{% url 'tasks:list' %}">Back to tasks</a>{% endblock %}
Refresh the list immediately after a successful create.
The task count stays the same.
The browser refreshes the redirected GET, not the previous POST. This is a normal navigation safeguard, not a universal duplicate-write guarantee.
A ModelForm must exclude server-controlled fields such as owner. Never use fields="__all__" here.
Likely cause: The new app migration has not been applied.
Check and correct: Check installed apps, run showmigrations tasks, then migrate.
Likely cause: The view may validate without saving or redirect to another page.
Check and correct: Trace is_valid, form.save and the task list query in order.
Add a priority choice field, its migration and ModelForm field.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
It defines the editing contract and prevents a future internal field from silently becoming user-editable.
All visitors share the task list. Persistence works, but ownership and authentication are deliberately introduced in the next project.