python / intermediate
Snippet
Django ModelForm Validierung mit clean() Methode
Die clean() Methode validiert über mehrere Felder hinweg. Sie wirft ValidationError für ungültige Kombinationen. Dies läuft nach feldspezifischen clean-Methoden und ermöglicht komplexe Geschäftsregel-Validierung.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django import formsfrom .models import Productclass ProductForm(forms.ModelForm):class Meta:model = Productfields = ['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
Erklärung
1
def clean(self)
Überschreiben für übergreifende Feldvalidierung
2
raise forms.ValidationError()
Djangos Standardweg um Validierungsfehler zu melden
3
price * stock > 1000000
Beispiel für Geschäftsregel-Validierung über verwandte Felder