Django Forms
Learn how to create and validate Django forms for handling user input in web applications. This is a foundational concept in Python web development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Python/Django experience. Take your time with each section and practice the examples
Understanding Django Forms
Django forms handle form rendering, validation, and data processing. They provide a secure and efficient way to handle user input in web applications.. This is an essential concept that every Python/Django developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Form Creation
# forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Post, Comment
# Basic form
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, widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Subject'
}))
message = forms.CharField(widget=forms.Textarea(attrs={
'class': 'form-control',
'rows': 5,
'placeholder': 'Your message'
}))
def clean_email(self):
email = self.cleaned_data.get('email')
if email and 'spam' in email:
raise forms.ValidationError("Spam emails are not allowed.")
return email
# Model form
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'category', 'published_date']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 10}),
'category': forms.Select(attrs={'class': 'form-control'}),
'published_date': forms.DateTimeInput(attrs={
'class': 'form-control',
'type': 'datetime-local'
})
}
def clean_title(self):
title = self.cleaned_data.get('title')
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters long.")
return title
# User registration form
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={
'class': 'form-control',
'placeholder': 'Email address'
}))
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control'})
}
# Comment form
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content']
widgets = {
'content': forms.Textarea(attrs={
'class': 'form-control',
'rows': 3,
'placeholder': 'Write your comment...'
})
}
# File upload form
class FileUploadForm(forms.Form):
title = forms.CharField(max_length=100)
description = forms.CharField(widget=forms.Textarea, required=False)
file = forms.FileField(
widget=forms.FileInput(attrs={'class': 'form-control'}),
help_text='Upload your file here'
)
def clean_file(self):
file = self.cleaned_data.get('file')
if file:
if file.size > 5 * 1024 * 1024: # 5MB limit
raise forms.ValidationError("File size must be under 5MB.")
if not file.name.endswith(('.pdf', '.doc', '.docx')):
raise forms.ValidationError("Only PDF and Word documents are allowed.")
return file