ModelForms: Create, Update, Delete¶
What we are learning¶
- What a ModelForm is versus a plain HTML form.
- How to render fields and validation errors.
- How to save valid data and redirect.
- How to delete safely through a confirmation POST.
Why this matters¶
This is the chapter where the site becomes editable. Same three-step dance every time: GET shows the form, POST validates, valid saves and redirects.
A simple explanation before code¶
An HTML form is just boxes in the browser. A ModelForm connects those boxes to the Task model: it renders fields, checks input, shows errors, and saves. You define which fields, Django does the repetitive work.
Important terms: ModelForm, validation, form.is_valid(), redirect-after-POST.
Step-by-step example¶
1. Define the form (15 min)¶
Create tasks/tasks/forms.py:
# inside tasks/forms.py (new file)
from django import forms
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ["name", "description", "priority", "done"]
Meta.model picks the table. fields whitelists what visitors may set (never include created_at).
2. Create and update views (25 min)¶
Extend tasks/tasks/views.py (add to the Ch3 file, keep index/task_detail):
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from .forms import TaskForm
@login_required
def task_create(request):
if request.method == "POST":
form = TaskForm(request.POST)
if form.is_valid():
task = form.save()
return redirect("task_detail", pk=task.pk)
else:
form = TaskForm()
return render(request, "task_form.html", {"form": form, "action": "Create"})
task_update is identical except it passes instance=task so the form edits instead of creating. Invalid POST skips the redirect and re-renders with errors. @login_required already guards these (fully taught in Ch7).
3. Templates and delete flow (20 min)¶
tasks/templates/task_form.html:
{% extends "base.html" %}
{% block title %}{{ action }} task | TaskRat{% endblock %}
{% block content %}
<h1>{{ action }} task</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{% if form.errors %}
<p>Please fix the errors above and submit again.</p>
{% endif %}
<button type="submit">{{ action }}</button>
</form>
<p><a href="{% url 'home_page' %}">Back to tasks</a></p>
{% endblock %}
tasks/templates/task_confirm_delete.html renders on GET and deletes only on POST:
{% extends "base.html" %}
{% block title %}Delete {{ task.name }} | TaskRat{% endblock %}
{% block content %}
<h1>Delete "{{ task.name }}"?</h1>
<p>This cannot be undone. Deleting happens only when you press the button below (a POST request).</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, delete</button>
</form>
<p><a href="{% url 'task_detail' task.pk %}">Cancel</a></p>
{% endblock %}
Routes in tasks/tasks/urls.py:
path("tasks/new/", views.task_create, name="task_create"),
path("tasks/<int:pk>/edit/", views.task_update, name="task_update"),
path("tasks/<int:pk>/delete/", views.task_delete, name="task_delete"),
Order matters: new/ sits before <int:pk>/ patterns in reading order so learners never confuse them (Django matches in order; new is not an int so it is safe either way, but the habit helps).
Let's build it: follow-along practical (15 min)¶
Create a task (lands on its detail page), submit an empty name (same page + "This field is required"), fix and resubmit, edit it, then open delete (GET shows question), confirm (POST deletes, lands on list).
What the code is doing¶
HTML form versus ModelForm: HTML collects strings; ModelForm validates against the model and saves. GET versus POST: GET shows blank/prefilled form; POST carries the data. form.save() writes the row. redirect after success stops double-submit on refresh.
Common mistakes and fixes¶
form.save()on invalid data — always gate onform.is_valid()first.- Missing
{% csrf_token %}— 403 on POST. - Delete works via link alone — your view deletes on GET. Move deletion inside
if request.method == "POST". task_create404/redirect loop for anonymous users — expected:@login_requiredsends them to login (Ch7 explains).
Try it yourself¶
Guided: submit each required field empty once and read the exact error. Independent: add help_text to one model field and confirm it appears in the form.
Check your understanding¶
- What connects a ModelForm to a table?
- What happens on invalid POST?
- Why redirect after a valid save?
- Why does delete need two steps (GET confirm + POST)?
- What does
instance=taskchange?
Summary¶
Define fields once, render with CSRF, validate, save, redirect. Deletes confirm on GET and act on POST.
Next lesson¶
We add accounts so only logged-in users reach these write views.