cleaned_data代码写在哪里?
时间: 2024-03-27 18:38:39 浏览: 16
`cleaned_data` 函数需要写在表单类中,用于对表单数据进行清洗和验证。具体来说,可以参考以下示例代码:
```
from django import forms
from django.core.exceptions import ValidationError
from .models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['name', 'age', 'height', 'weight']
def clean_height(self):
height = self.cleaned_data.get('height')
if height and height < 100:
raise ValidationError('请输入正确的身高(cm)')
return height
def clean_weight(self):
weight = self.cleaned_data.get('weight')
if weight and weight < 20:
raise ValidationError('请输入正确的体重(kg)')
return weight
def cleaned_data(self):
super().cleaned_data()
height = self.cleaned_data.get('height')
weight = self.cleaned_data.get('weight')
if height and weight and height / weight < 1.5:
raise ValidationError('身高体重比例不符合要求')
return self.cleaned_data
```
在这段代码中,`clean_height` 和 `clean_weight` 分别对身高和体重进行验证,如果不符合要求,则会抛出 `ValidationError` 异常。而 `cleaned_data` 函数则用于对表单数据进行整体验证,如果身高体重比例不符合要求,则会抛出 `ValidationError` 异常。需要注意的是,`cleaned_data` 函数需要在所有字段的验证函数执行完毕后执行,以确保表单数据的完整性。