在Django表单上引发自定义验证错误的问题

时间:2013-05-07 23:53:29

标签: django django-forms validation

我有一个基本的注册表单,其中包含一个BooleanField,供人们接受条款和隐私政策。我想要做的是更改用户不检查时引发的ValidationError的语言。

class RegisterForm(forms.Form):
    username = forms.CharField(label="Username")
    email = forms.EmailField(label="Email")
    location = forms.CharField(label="Location",required=False)
    headline = forms.CharField(label="Headline",required=False)
    password = forms.CharField(widget=forms.PasswordInput,label="Password")
    confirm_password = forms.CharField(widget=forms.PasswordInput,label="Confirm Password")
    terms = TermsField(label=mark_safe("I have read and understand the <a href='/terms'>Terms of Service</a> and <a href='/privacy'>Privacy Policy</a>."),required=True)

TermsFieldBooleanField

的子类
class TermsField(forms.BooleanField):
    "Check that user agreed, return custom message."

    def validate(self,value):
        if not value:
            raise forms.ValidationError('You must agree to the Terms of Service and Privacy Policy to use this site.')
        else:    
            super(TermsField, self).validate(value)

它正确验证,如果用户没有检查它们,则表单不会验证,而是返回通用的“此字段是必需的”错误。这似乎是一个非常简单的任务,我确信我做的事情基本上是错误的。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

这是因为Django认为该字段是必需的,并且没有提供任何值,因此它甚至不需要调用您的validate方法(在内置验证之后)。

实现你想要完成的目标的方法是:

class RegisterForm(forms.Form):
    # ...other fields
    terms = forms.BooleanField(
        required=True,
        label=mark_safe('I have read and understand the <a href=\'/terms\'>Terms of Service</a> and <a href=\'/privacy\'>Privacy Policy</a>.')
        error_messages={'required': 'You must agree to the Terms of Service and Privacy Policy to use Prospr.me.'}
    )

这将覆盖Field.default_error_messages中定义的默认“必需”消息。