model.py
from django.core.exceptions import ValidationError
def surname_validate(value):
if value == "123":
raise ValidationError('is not an even number')
class Member(models.Model):
surname=models.CharField(max_length=50,validators=[surname_validate])
other_names=models.CharField(max_length=150,null=True, blank=True)
forms.py
class MemberEditForm(forms.ModelForm):
class Meta:
model=Member
当我尝试保存没有输入的表单时,我得到默认的“此字段是必需的”错误,所以我知道我的观点是正确的。问题是我对姓氏字段的验证根本不起作用,我不明白。我在这做错了什么。为什么不工作?这令人沮丧
答案 0 :(得分:0)
实际上Model Validation
不适用于ModelForm
。如果要在表单中对surname
进行验证,则必须在其清洁方法中为表单编写验证。
所以,你的表格必须是这样的:
class MemberEditForm(forms.ModelForm):
class Meta:
model = Member
surname = forms.CharField(max_length = 50, required = True, error_messages = {'my_error': 'is not an even number'})
def clean_surname(self):
if self.cleaned_data['surname'] == '123':
raise ValidationError(self.fields['surname'].error_messages['my_error'])
return self.cleaned_data['surname']
答案 1 :(得分:0)
我终于使用了它并且它起作用了
attrs_dict = {'class': 'required'}
class MemberEditForm(forms.ModelForm):
class Meta:
model = Member
surname = forms.RegexField(#regex=r'^[\w.@+-]+$',
regex=r'^$',# my validation here
max_length=50,
widget=forms.TextInput(attrs=attrs_dict),
label=_("Surname*"),
error_messages={'invalid': _("Invalid Entry.")})
由于