简体   繁体   English

Django:覆盖 UserCreationForm 上的 form.errors 消息

[英]Django: Override form.errors messages on UserCreationForm

I'm trying to override (add languages) the messages of form.errors.我正在尝试覆盖(添加语言)form.errors 的消息。 I've tried this:我试过这个:

forms.py forms.py

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']


    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)
        self.error_messages['duplicate_username'] = 'some message'

After the form is submitted, it's not saved because username are unique and the error is displayed on the template.表单提交后没有保存,因为用户名是唯一的,并且模板上显示错误。 I'd like to make the same with the password but I can't find out the errors' key for each password validation.我想对密码做同样的事情,但我找不到每个密码验证的错误密钥。 Can you provide me it?你能提供给我吗?

set error_messages --(Django doc) attribute in Meta class as,将 Meta class 中的error_messages --(Django doc)属性设置为,

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
        error_messages = { 'username': { 'unique': 'Your Custom Error Message here !!!', }, }

If you want to override the password mismatch error message, override the error_messages attribute in the form class (not in the Meta class) as below,如果要覆盖密码不匹配错误消息,请覆盖格式为 class(不在Meta类中)的error_messages属性,如下所示,

class CreateUserForm(UserCreationForm):
    error_messages = { 'password_mismatch': "Your Password Mismatch For 'UserCreationForm' class", }
    # other code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM