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

tch*_*ore 2 django validation django-forms

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

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)
Run Code Online (Sandbox Code Playgroud)

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

oro*_*aki 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.'}
    )
Run Code Online (Sandbox Code Playgroud)

这将覆盖Field.default_error_messages.