0

模型.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)

表格.py

class MemberEditForm(forms.ModelForm):
class Meta:
    model=Member

当我尝试保存没有输入的表单时,我收到默认的“此字段是必需的”错误,所以我知道我的观点是正确的。问题是我对姓氏字段的验证根本不起作用,我不明白。我在这里做错了什么。为什么它不起作用???这令人沮丧

4

2 回答 2

0

其实Model Validation不为ModelForm。如果要surname在表单中进行验证,则必须在其 clean 方法中为表单编写验证。

所以,你的表格必须是这样的:

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']
于 2013-01-22T10:03:54.803 回答
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.")})

谢谢

于 2013-01-24T12:28:25.493 回答