**form_obj.cleaned_data 中的 **代表什么意思?
时间: 2023-09-12 16:12:43 浏览: 157
`form_obj.cleaned_data` 中的 `cleaned_data` 表示经过表单验证后,清洁过的数据。在 Django 中,当用户提交表单数据时,Django 会自动验证这些数据。如果数据通过了验证,它将会被存储在 `cleaned_data` 字典中。这个字典包含了所有验证成功的字段和对应的值,可以通过这个字典来获取用户输入的有效数据。
相关问题
我写了下述代码用于检查紧急联系人的电话号码是否合法,但是在我在admin中为一个员工添加一个紧急联系人时,他不会报错,我需要怎么修改?class EmergencyAdmin(admin.ModelAdmin): list_display = ['staff_name', 'name', 'tel'] search_fields = ['res_id__NAME',] # 找到外键对应的表中的属性 def staff_name(self, obj): return obj.res_id.NAME # 将这个属性的标题行进行重命名 staff_name.short_description = '员工姓名' def formfield_for_dbfield(self, db_field, **kwargs) : formfield = super().formfield_for_dbfield(db_field, **kwargs) # 电话号码有效性验证 if db_field.name == 'tel' and isinstance(formfield.widget, TextInput): def validate_tel(value): if not value.isdigit() or len(value) != 11: raise ValidationError('请输入有效手机号码') formfield.widget.input_type = 'TEL' formfield.validators.append(validate_tel) return formfield
您可以尝试在EmergencyAdmin中添加一个clean()方法,以确保对于添加紧急联系人时输入的电话号码进行验证。例如:
```python
class EmergencyAdmin(admin.ModelAdmin):
list_display = ['staff_name', 'name', 'tel']
search_fields = ['res_id__NAME',]
def staff_name(self, obj):
return obj.res_id.NAME
staff_name.short_description = '员工姓名'
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super().formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'tel' and isinstance(formfield.widget, TextInput):
formfield.widget.input_type = 'TEL'
formfield.validators.append(validate_tel)
return formfield
def clean(self):
super().clean()
for form_data in self.cleaned_data:
if 'tel' in form_data:
tel = form_data['tel']
if not tel.isdigit() or len(tel) != 11:
raise forms.ValidationError('请输入有效手机号码')
```
这样,当您在添加一个紧急联系人时,如果输入的电话号码无效,将会抛出一个ValidationError。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)