我写了下述代码用于检查紧急联系人的电话号码是否合法,但是在我在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
时间: 2024-03-27 16:39:41 浏览: 81
您可以尝试在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。
阅读全文