0 day streak
python / intermediate
Snippet

Django ModelForm Custom Validation with clean()

The clean() method validates across multiple fields. It raises ValidationError for invalid combinations. This runs after field-specific clean methods and enables complex business rule validation.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'price', 'stock']
def clean(self):
cleaned_data = super().clean()
price = cleaned_data.get('price')
stock = cleaned_data.get('stock')
if price and price < 0:
raise forms.ValidationError('Price cannot be negative')
if stock is not None and stock < 0:
raise forms.ValidationError('Stock cannot be negative')
if price and stock and price * stock > 1000000:
raise forms.ValidationError('Inventory value exceeds limit')
return cleaned_data
django
Breakdown
1
def clean(self)
Override to implement cross-field validation logic
2
raise forms.ValidationError()
Django's standard way to signal validation failures
3
price * stock > 1000000
Example of business rule validation across related fields