2

我有一个基本的注册表单,其中包括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)

TermsField从以下子类化BooleanField

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)

它可以正确验证,因为如果用户不检查它们的术语字段,则表单不会验证,但它会返回通用的“此字段是必需的”错误。这似乎是一项非常简单的任务,我确信我做错了一些基本的事情。有任何想法吗?

4

1 回答 1

5

这是因为 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

于 2013-05-08T01:24:46.090 回答