Python Tutorial
Django Forms
ModelForm builds an HTML form from a model. Validate POST data, save, and redirect.
ModelForm
# members/forms.py
from django import forms
from .models import Member
class MemberForm(forms.ModelForm):
class Meta:
model = Member
fields = ["firstname", "lastname", "phone"]View
from django.shortcuts import redirect, render
from .forms import MemberForm
def add_member(request):
if request.method == "POST":
form = MemberForm(request.POST)
if form.is_valid():
form.save()
return redirect("members")
else:
form = MemberForm()
return render(request, "members/add.html", {"form": form})Template
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>Always include csrf_token on POST forms. Django rejects the request without it.
📘 Real-World Deep Dive
Knowing <strong>Django Forms (Django)</strong> well is what turns Django from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Django Forms that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from django import forms
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ["title", "author", "pages", "pub"]
def clean_pages(self):
n = self.cleaned_data["pages"]
if n <= 0: raise forms.ValidationError("Pages must be positive.")
return nExpected Output
(no output)Common mistakes
- Forgetting to call
.save()on a model instance after mutation silently persists nothing. - Reading every row with
Model.objects.all()on a 1 M-row table OOMs the worker — use.iterator()for streaming. - Queries inside loops produce N+1 problems — pull related rows with
select_related/prefetch_related. - Treating Django Forms as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Add database indexes (
db_index=TrueorMeta.indexes) on columns used infilter. - Use
cache_pageon read-heavy views and setCONN_MAX_AGEto keep DB connections warm. - Generate migrations with
python manage.py makemigrations --dry-run --verbosity 3and review before committing. - When working with Django, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.