Django Forms (Form class)
Django forms handle HTML form rendering, user input validation, and data cleaning. The Form class defines fields, validation rules, and widgets. Forms separate presentation from validation, making your code clean and secure.
20 min•By Priygop Team•Updated 2026
Form Basics
- from django import forms
- Define fields: CharField, EmailField, IntegerField, etc.
- Forms validate data automatically based on field types
- form.is_valid() — True if all fields pass validation
- form.cleaned_data — Dictionary of validated data
- form.errors — Dictionary of validation errors
- Render forms in templates: {{ form.as_p }}, {{ form.as_div }}
Form Example
Form Example
# blog/forms.py
# from django import forms
# class ContactForm(forms.Form):
# name = forms.CharField(
# max_length=100,
# widget=forms.TextInput(attrs={
# 'class': 'form-control',
# 'placeholder': 'Your Name'
# })
# )
# email = forms.EmailField(
# widget=forms.EmailInput(attrs={
# 'class': 'form-control',
# 'placeholder': 'your@email.com'
# })
# )
# subject = forms.CharField(max_length=200)
# message = forms.CharField(
# widget=forms.Textarea(attrs={
# 'class': 'form-control',
# 'rows': 5,
# 'placeholder': 'Your message...'
# })
# )
# blog/views.py
# def contact(request):
# if request.method == 'POST':
# form = ContactForm(request.POST)
# if form.is_valid():
# name = form.cleaned_data['name']
# email = form.cleaned_data['email']
# message = form.cleaned_data['message']
# # Send email, save to DB, etc.
# return redirect('success')
# else:
# form = ContactForm()
# return render(request, 'contact.html', {'form': form})Tip
Tip
Use Class-Based Views (CBVs) for standard CRUD patterns. ListView, DetailView, CreateView save massive amounts of code.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not using .as_view() when adding CBVs to urlpatterns. path('posts/', PostList.as_view()) — the .as_view() is required.
Practice Task
Note
(1) Create a ListView for posts. (2) Add a DetailView for single post. (3) Use template_name to set custom templates.
Quick Quiz
Key Takeaways
- Django forms handle HTML form rendering, user input validation, and data cleaning.
- from django import forms
- Define fields: CharField, EmailField, IntegerField, etc.
- Forms validate data automatically based on field types