gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:04:47 25 4
gpt4 key购买 nike

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

如果用户不检查 TermsField,它会正确验证,表单不会验证,但它会返回一般的“此字段是必需的”错误。这似乎是一项非常简单的任务,而且我确定我做错了一些基本错误。有什么想法吗?

最佳答案

这是因为 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 中定义的默认“必需”消息。

关于django - 在 Django 表单上引发自定义验证错误的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16430482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com