【问题标题】:How do we customise the password fields not matching in Django?我们如何自定义 Django 中不匹配的密码字段?
【发布时间】:2020-11-06 15:13:24
【问题描述】:

我想知道我们如何自定义在 Django 中内置的 UserCreationForm 的 password1 和 password2 字段中输入 2 个不同的密码时显示的错误消息。这个我试过了

def __init__(self,*args, **kwargs):
    super(CreateUserForm,self).__init__(*args, **kwargs)

    self.fields['password2'].error_messages.update({
        'unique': 'Type smtn here!'
    })

我在这个过程中做错了吗?在我的模板中,这是错误消息的代码。

<span id="error">{{form.errors}}</span>

请告诉我是否有其他方法可以做到这一点。我正在使用模型表单。

class CreateUserForm(UserCreationForm):
  class Meta:
    model = User
    fields = ['username','email','password1','password2']
  def __init__(self,*args, **kwargs):
    super(CreateUserForm,self).__init__(*args, **kwargs)

    self.fields['password2'].error_messages.update({
        'unique': 'Type smtn here!'
    })

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    正如您在the source code of django's UserCreationForm 中看到的那样。

    此错误消息由clean_password2() 触发并使用self.error_messages['password_mismatch']。这意味着您基本上必须在子表单中覆盖 error_messages

    class CreateUserForm(UserCreationForm):
    
        error_messages = {
            'password_mismatch': 'Type smtn here!',
        }
    

    或者,如果您想确保不丢失error_messages dict 中可能存在的其他条目(尽管它目前是唯一的条目),您也可以更新__init__ 中的dict:

    class CreateUserForm(UserCreationForm):
    
        def __init__(self, *args, **kwargs):
            self.error_messages['password_mismatch'] = 'Type smtn here!'
            super().__init__(*args, **kwargs)
    

    【讨论】:

    • 应该放在 Meta 类内部还是外部?另外,谢谢你的回答,我试试看!
    • 在元之外。
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多