Django
Beginner
1 min read
Django Forms and Form Validation
Example
# blog/forms.py — form definition and validation
from django import forms
from django.core.exceptions import ValidationError
from .models import Post
def no_spam_words(value):
"""Custom validator: reject values containing spam keywords."""
spam_words = ['buy now', 'click here', 'free money']
lower = value.lower()
for word in spam_words:
if word in lower:
raise ValidationError(f'Content contains a disallowed phrase: "{word}".')
class PostForm(forms.Form):
title = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Post title'}),
)
body = forms.CharField(
widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 8}),
validators=[no_spam_words],
)
tags = forms.CharField(
max_length=200,
required=False,
help_text='Comma-separated tag names.',
)
def clean_title(self):
title = self.cleaned_data['title']
if Post.objects.filter(title__iexact=title).exists():
raise ValidationError('A post with this title already exists.')
return title.strip().title()
def clean(self):
cleaned = super().clean()
title = cleaned.get('title', '')
body = cleaned.get('body', '')
# Cross-field: body must not just repeat the title
if body.strip().lower() == title.strip().lower():
raise ValidationError('The post body must contain more than just the title.')
return cleaned
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django