Forms, the admin and class-based views
Three of Django's biggest time-savers: forms validate user input and render HTML fields, the admin gives you a complete back office for free, and class-based views implement common page types (lists, details, create/update/delete) in a few lines.
Forms
A Form class declares fields, validates submitted data, and reports errors per field:
is_valid()runs every check; thencleaned_dataholds converted values ("31"became the int31).clean_<field>()methods validate one field;clean()checks fields against each other.- Rendering
{{ form }}in a template outputs all labels, inputs and error messages.
ModelForms
Most forms create or edit a model. A ModelForm builds its fields from the model, including its validation, and can save directly:
The uniqueness check (unique=True) and the non-negative stock (PositiveIntegerField) came from the model, for free. Listing fields explicitly matters: it stops users from setting fields you didn't intend to expose (mass assignment).
The classic form view
def create_product(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
product = form.save()
return redirect("product_detail", pk=product.pk) # POST → redirect → GET
else:
form = ProductForm()
return render(request, "products/form.html", {"form": form}) # invalid forms re-render with errors<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Save</button>
</form>The admin
Django's admin site is a full CRUD interface for your models, with search, filters and permissions, generated from your model definitions. Register models in admin.py:
# shop/admin.py
from django.contrib import admin
from .models import Product
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ["name", "price", "stock", "in_stock"]
list_filter = ["stock"]
search_fields = ["name"]
list_editable = ["price", "stock"]
ordering = ["name"]
@admin.display(boolean=True)
def in_stock(self, obj):
return obj.stock > 0python manage.py createsuperuser
python manage.py runserver # then open http://127.0.0.1:8000/admin/Let's check that it works by logging in as a superuser with the test client:
The admin is meant for staff (editors, support, operations), not for customers. Restrict it to trusted users, give staff accounts only the model permissions they need, and consider moving it from /admin/ to a less obvious URL.
Class-based views
Common views follow the same pattern every time, so Django provides generic class-based views:
ListView handled the query, ordering and pagination; CreateView built the form, validated it, saved the object and redirected. Use function views when the logic is unusual, and generic views when it's standard.
Practice
- Add a
ContactFormwithname,emailandmessage(at least 20 characters) and print its errors for an invalid submission. - Add an
UpdateViewand aDeleteViewfor products (withsuccess_url = reverse_lazy("product_list")). - In the admin, add
list_filterand a customin_stockcolumn.
1.When does a Django form's cleaned_data contain the converted values?
2.Why list fields explicitly in a ModelForm's Meta?
3.What does a generic ListView give you?