覆盖password_validation消息 [英] override password_validation messages

查看:122
本文介绍了覆盖password_validation消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用UserCreationForm创建新用户。

I use UserCreationForm to create new users.

from django.contrib.auth.forms import UserCreationForm

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

UserCreationForm 自动添加两个字段( Password1 Password2 )。
如果密码太短则提示错误。还是太简单或太普遍。通过 django.contrib.auth.password_validation 完成。

UserCreationForm automatically adds two fields (Password1 and Password2). If the password is too short then it raises an error, telling that. Or if it is too simple or common. It is done via django.contrib.auth.password_validation.

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

I wonder if I can override the messages of these errors.

现在,密码验证的源代码为:

right now the source code for password validation is:

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保持不变:

but when I try to use this code in form definition to override this error message the label changes, but error_messages remain the same:

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

我在做什么错?

推荐答案

更新:子类而不是复制/粘贴可能是一个更好的解决方案。请参见古斯塔沃的答案

Update: Sub-classing instead of copying/pasting is probably a better solution. See gustavo's answer.

请参见如何在django auth密码验证器旁边使用自定义密码验证器? / a>以获得类似的说明。

See How to use custom password validators beside the django auth password validators? for similar instructions.

我一直在寻找相同的东西,但我认为无法通过任何方式更改密码验证器上的错误消息表单级别。您可能最终不得不编写自己的自定义验证器,然后将其包含在 settings.py 中的 AUTH_PASSWORD_VALIDATORS 中(这就是我所做的)。我的操作方法如下:

I've been looking around for the same thing and I don't think there's any way to change the error message on password validators from the form level. You'll probably end up having to write your own custom validator and then including it in your AUTH_PASSWORD_VALIDATORS in settings.py (which is what I did). Here's how I did it:

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

1. Go to django's built-in password validators and copy the MinimumLengthValidator code. Here's the link: https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator

2。。创建python文件放入您选择的应用程序(我选择了我的基本应用程序)中,并给它起您选择的名称(我的名字是 custom_validators.py
我的看起来像这样:

2. Create a python file in the app of your choosing (I chose my base app) and give it the name of your choosing (mine is custom_validators.py) Mine looks like this:

    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。 settings.py ,在您的 AUTH_PASSWORD_VALIDATORS 中注释掉以下几行:

3. In settings.py, comment out the following lines in your AUTH_PASSWORD_VALIDATORS :

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

并添加以下行:

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

现在,只要您运行 validate() form.is_valid()(也会运行 validate ()),您的密码将通过新的自定义密码验证程序,而不是django的默认密码验证程序。可能需要进行一些调整,但是您可能可以对所有django的默认验证器进行检查。

Now, whenever you run validate() or form.is_valid() (which also runs validate()) your password will go through your new custom password validator instead of django's default one. It might take some tweaking, but you could probably go through and do this for all of django's default validators.

希望有帮助!

这篇关于覆盖password_validation消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆