覆盖password_validation消息

2024-02-15

我使用 UserCreationForm 来创建新用户。

from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):
      class Meta:
       model = User
       fields = ['username', 'first_name', 'last_name', 'email',  'is_active']

UserCreationForm自动添加两个字段(1个密码 and 密码2)。 如果密码太短,则会引发错误并提示这一点。或者如果它太简单或常见。它是通过以下方式完成的django.contrib.auth.password_validation.

我想知道是否可以覆盖这些错误的消息。

现在密码验证的源代码是:

def validate(self, password, user=None):
    if len(password) < self.min_length:
        raise ValidationError(
            ungettext(
                "This password is too short. It must contain at least %(min_length)d character.",
                "This password is too short. It must contain at least %(min_length)d characters.",
                self.min_length
            ),
            code='password_too_short',
            params={'min_length': self.min_length},
        )

但是当我尝试在表单定义中使用此代码来覆盖此错误消息时,标签会发生变化,但 error_messages 保持不变:

password1 = forms.CharField(label='New Label', error_messages={'password_too_short': 'My error message for too short passwords'})

我究竟做错了什么?


更新:子类化而不是复制/粘贴可能是更好的解决方案。看古斯塔沃的回答 https://stackoverflow.com/a/54442904/9638991.

See 除了 django auth 密码验证器之外,如何使用自定义密码验证器? https://stackoverflow.com/questions/43915518/how-to-use-custom-password-validators-beside-the-django-auth-password-validators类似的说明。

我一直在寻找同样的事情,但我认为没有任何方法可以从表单级别更改密码验证器上的错误消息。您可能最终不得不编写自己的自定义验证器,然后将其包含在您的AUTH_PASSWORD_VALIDATORS in settings.py(这就是我所做的)。我是这样做的:

1.转到 django 的内置密码验证器并复制 MaximumLengthValidator 代码。这是链接:https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator

2.在您选择的应用程序(我选择了我的基本应用程序)中创建一个 python 文件,并为其指定您选择的名称(我的是custom_validators.py) 我的看起来像这样:

    from django.utils.translation import ngettext  # https://docs.python.org/2/library/gettext.html#gettext.ngettext
    from django.core.exceptions import ValidationError

    # https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator
    class MyCustomMinimumLengthValidator(object):
        def __init__(self, min_length=8):  # put default min_length here
            self.min_length = min_length

        def validate(self, password, user=None):
            if len(password) < self.min_length:
                raise ValidationError(
                    ngettext(
                        # silly, I know, but if your min length is one, put your message here
                        "This password is too short. It must contain at least %(min_length)d character.",
                        # if it's more than one (which it probably is) put your message here
                        "This password is too short. It must contain at least %(min_length)d characters.",
                        self.min_length
                    ),
                code='password_too_short',
                params={'min_length': self.min_length},
                )

        def get_help_text(self):
            return ngettext(
                # you can also change the help text to whatever you want for use in the templates (password.help_text)
                "Your password must contain at least %(min_length)d character.",
                "Your password must contain at least %(min_length)d characters.",
                self.min_length
            ) % {'min_length': self.min_length}

3. In settings.py,注释掉您的以下行AUTH_PASSWORD_VALIDATORS :

    # {
    #     'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    # },

并添加以下行:

{
    'NAME': 'base.custom_validators.MyCustomMinimumLengthValidator',
            # app_name.file_name.validator_name
},

现在,每当你跑步时validate() or form.is_valid()(它也运行validate())您的密码将通过新的自定义密码验证器而不是 django 的默认密码验证器。这可能需要一些调整,但您可能可以对 django 的所有默认验证器执行此操作。

希望有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

覆盖password_validation消息 的相关文章

随机推荐