django 无法导入验证程序检查AUTH_PASSWORD_VALIDATORS设置

thtygnil  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(108)

我做了validators.py并添加了我的自定义密码验证器,如检查密码和特殊字符,之后我在我的settings.py中添加了这些验证器,如下所示

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
'OPTIONS': {
'max_similarity': 0.7,
'user_attributes': ("username", "first_name", "last_name", "email")
}
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {
'min_length': 8,
}
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
\# custom coded validators
{
'NAME': 'app1.validators.UppercaseValidator',
},
{
'NAME': 'app1.validators.SpecialCharValidator',
},
]

这是我的forms.py
`

from django import forms from django.contrib.auth.password_validation import validate_password class SignupForm(forms.Form):
     firstname = forms.CharField(max_length=20)     
     lastname = forms.CharField(max_length=20)     
     email = forms.EmailField()
     username = forms.CharField(max_length=30)
     password = forms.CharField(widget=forms.PasswordInput, validators=[validate_password])`

而注册IM得到这个错误
ImproperlyConfigured at /signup/ The module in NAME could not be imported: app1.validators.UppercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting.
如有任何帮助,我们将不胜感激
在它给我基于django默认的验证器的错误之前,但是在添加了我自己的验证器之后,它给了我我提到的错误。

f1tvaqid

f1tvaqid1#

我在运行我的django示例时也遇到了同样的问题,它在版本(3,2,19,'final',0)时工作正常,而在版本(4,1,7,'final',0)时中断。下面是我的验证码:

import re
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _

class UppercaseValidator:
    def validate(self, password, user=None):
        if not re.findall('[A-Z]', password):
            raise ValidationError(
                _("The password must contain at least 1 uppercase letter, A-Z."),
            code='password_no_upper',
        )

def get_help_text(self):
    return _(
        "Your password must contain at least 1 uppercase letter, A-Z."
    )

这里是我的settings.py:

AUTH_PASSWORD_VALIDATORS = [
   # custom coded validators
   {'NAME': 'users.validators.UppercaseValidator',},
   ... 
]

所以我把验证移到了serializer.py中,在www.example.com中注解代码settings.py,它工作了。这里的代码我的serializer.py:

import re
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _

class CustomRegisterSerializer(RegisterSerializer):

    def validate(self, data):
        user = User(**data)
        password = data.get('password')
        try:
            if not re.findall('[A-Z]', password):
               raise serializers.ValidationError("The password must contain at least 1 uppercase letter, A-Z.")
        except Exception as e:
            raise serializers.ValidationError("The password must contain at least 1 uppercase letter, A-Z.")

希望这能帮到你!

相关问题