ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Django Tutorial• 8 min read

Forms, ModelForms & CSRF Defense

Automated HTML form generation, server-side validation, and security tokens

Handling HTML forms is traditionally tedious and prone to security oversights. Django provides Form and ModelForm classes to generate HTML, sanitize submissions, validate business rules, and save directly to models.

ModelForms and Cross-Site Request Forgery (CSRF)

ModelForm: Automatically builds form fields, validation logic, and error messages derived directly from your model definition.

form.is_valid(): Executes validation rules and populates form.cleaned_data.

CSRF Protection: Django requires the {% csrf_token %} template tag inside all POST forms. It embeds a secret token validated by the CSRF middleware to block malicious cross-origin form submissions.

ModelForm Definition and View Handling
# forms.py
from django import forms
from .models import Course

class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ['title', 'description', 'price', 'category']

# views.py
from django.shortcuts import render, redirect
from .forms import CourseForm

def create_course(request):
    if request.method == 'POST':
        form = CourseForm(request.POST)
        if form.is_valid():
            new_course = form.save() # Saves record to database
            return redirect('course_detail', pk=new_course.pk)
    else:
        form = CourseForm()

    return render(request, 'courses/form.html', {'form': form})
ModelForm eliminates repetitive HTML form markup and manual parameter validation.
Warning / Pitfall

Omitting {% csrf_token %} from an HTML POST form in Django will trigger an immediate 403 Forbidden CSRF verification failure.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which template tag MUST be included inside all POST forms in Django templates to avoid a 403 Forbidden error?