ModelForm 支持 clean_<fieldname> 吗?
Is clean_<fieldname> supported in ModelForm?
在 ModelForm 的 documentation 中被告知,要对表单执行自定义验证,必须覆盖 .clean()
方法。
但是,我更愿意使用 clean_<fieldname>
方法,因为我只需要验证一个字段。这适用于标准 forms.Form
但没有提及 forms.ModelForm
.
Django 支持这种方法吗?
是的,当然。请参阅下面给出的示例。
class UserForm(form.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'website', 'twitter','facebook', 'linkedin',
'glassdoor', 'github',)
def clean_github(self):
github = self.cleaned_data.get('github')
if github and not re.match(r'^[a-zA-Z0-9-]+$', github):
raise forms.ValidationError('Please enter a valid github username')
return github
在 ModelForm 的 documentation 中被告知,要对表单执行自定义验证,必须覆盖 .clean()
方法。
但是,我更愿意使用 clean_<fieldname>
方法,因为我只需要验证一个字段。这适用于标准 forms.Form
但没有提及 forms.ModelForm
.
Django 支持这种方法吗?
是的,当然。请参阅下面给出的示例。
class UserForm(form.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'website', 'twitter','facebook', 'linkedin',
'glassdoor', 'github',)
def clean_github(self):
github = self.cleaned_data.get('github')
if github and not re.match(r'^[a-zA-Z0-9-]+$', github):
raise forms.ValidationError('Please enter a valid github username')
return github