Skip to lesson content

PROJECT 4 · LESSON 7 OF 16

Create a persistent task application

Add a second Django app and use a ModelForm to validate and save records.

  • app boundaries
  • ModelForm
  • cleaned_data
  • create/read

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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 begins with a small data model

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.

ModelForm connects validation to a model

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.

The redirect separates writing from reading

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.

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. GET /tasks/ queries tasks and renders the current list.

  2. GET create displays an unbound TaskForm.

  3. POST create binds and validates submitted fields.

  4. A valid form saves one task; an invalid form returns errors without saving.

  5. A redirect performs a fresh list GET, showing the stored record.

Observe a database write

  1. Create a task called Read Django forms.
  2. Restart the development server and return to the list; the task remains.
  3. Submit a whitespace-only title. No second record should be created.

3. Build it, one file at a time

  1. Run python manage.py startapp tasks if starting manually, then register tasks using the settings file below. Create the templates and app URL configuration.
  2. Apply the included migration. Add a task through /tasks/new/ and confirm that /tasks/ shows it.
  3. Restart runserver and verify the record persists. Try submitting whitespace-only text.
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',
]
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

Dispatch incoming paths to the correct application.

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

Read the code

  1. Django tries URL patterns in order. include delegates the remaining path to an app-level URL configuration.
  2. The admin has its own URL configuration. Naming and namespacing application routes avoids embedding path strings throughout templates.

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

tasks/__init__.py

Create a separate Python app for task features.

tasks/__init__.py

Read the code

  1. Keeping task-specific modules together makes their responsibilities easier to inspect.

tasks/models.py

Define persistent task data and a future ownership relationship.

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

Read the code

  1. auto_now_add records the creation time on insertion. Meta ordering gives newest tasks first.
  2. owner references the configured auth model rather than importing a particular User class. Null is allowed only to preserve the shared lab stage.

tasks/migrations/__init__.py

Enable task migrations.

tasks/migrations/__init__.py

Read the code

  1. This intentionally empty package is required for normal migration discovery.

tasks/migrations/0001_initial.py

Create the task table after the auth user table exists.

tasks/migrations/0001_initial.py
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"]})]

Read the code

  1. The swappable dependency points at the configured user model’s schema.
  2. The owner column already exists, so introducing privacy later changes behavior without assigning old records to arbitrary users.

tasks/forms.py

Generate a form for only the user-editable task fields.

tasks/forms.py
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 the code

  1. The explicit fields list excludes owner and created_at. A visitor cannot assign ownership by adding an input.
  2. clean_title normalizes valid text and rejects a blank title on the server.

tasks/views.py

Read all shared lab tasks and save a valid creation form.

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

Read the code

  1. TaskForm(request.POST) binds submitted values; an unbound form renders blank inputs.
  2. form.save creates the model only after is_valid succeeds. Redirect after success implements Post/Redirect/Get.

tasks/urls.py

Give the app its own namespaced list and create routes.

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

Read the code

  1. The project supplies the /tasks/ prefix. These app routes handle the remainder.

templates/tasks/list.html

Render persistent task rows or an empty state.

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

Read the code

  1. The queryset is provided by the view. The yesno filter translates a boolean into a friendly status.

templates/tasks/form.html

Use one form template for create now and edit later.

templates/tasks/form.html
{% 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 %}

Read the code

  1. The heading and bound form are supplied by the view. csrf_token protects the POST request.

4. Run it and check your result

  • A valid task survives refreshing and restarting Django.
  • Invalid titles redisplay errors without creating records.

5. Predict, change and observe

Refresh the list immediately after a successful create.

Compare your prediction with the expected result

What you should observe

The task count stays the same.

Why it happens

The browser refreshes the redirected GET, not the previous POST. This is a normal navigation safeguard, not a universal duplicate-write guarantee.

6. Troubleshoot with evidence

A common mistake

A ModelForm must exclude server-controlled fields such as owner. Never use fields="__all__" here.

Tasks table missing

Likely cause: The new app migration has not been applied.

Check and correct: Check installed apps, run showmigrations tasks, then migrate.

A valid title does not appear

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.

7. Practice and explain it back

Your independent task

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.

Why specify ModelForm fields explicitly?

It defines the editing contract and prevents a future internal field from silently becoming user-editable.

Why is this stage local-only?

All visitors share the task list. Persistence works, but ownership and authentication are deliberately introduced in the next project.