Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Intermediate

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:

Python · editable
  • is_valid() runs every check; then cleaned_data holds converted values ("31" became the int 31).
  • 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:

Python · editable

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

python
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
html
<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:

python
# 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 > 0
bash
python 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:

Python · editable

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:

Python · editable

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

  1. Add a ContactForm with name, email and message (at least 20 characters) and print its errors for an invalid submission.
  2. Add an UpdateView and a DeleteView for products (with success_url = reverse_lazy("product_list")).
  3. In the admin, add list_filter and a custom in_stock column.
✎ Check your understanding

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?

← Django views, URLs and templates