How can I set a minimum password length when using the built-in Django auth module?

前端 未结 5 858
南方客
南方客 2021-01-01 21:25

I’m implementing authentication in a Django site using the built-in auth module, including the built-in UserCreationForm.

I’d like to set a minimum length for passwo

相关标签:
5条回答
  • 2021-01-01 21:46

    /django/contrib/auth/password_validation.py Contains class MinimumLengthValidator with default the password minimum length:

    class MinimumLengthValidator(object):
        """
        Validate whether the password is of a minimum length.
        """
        def __init__(self, min_length=8):
            self.min_length = min_length
    
        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},
                )
    
        def get_help_text(self):
            return ungettext(
                "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}
    
    0 讨论(0)
  • 2021-01-01 21:47

    Especially if you're already using a sub-classed UserCreationForm, I'd say you should definitely just add the validation to it. You should be able to override the clean_password method on the form:

    def clean_password(self):
        password = self.cleaned_data.get('password1')
        if len(password) < 8:
            raise ValidationError('Password too short')
        return super(MyUserCreationForm, self).clean_password1()
    
    0 讨论(0)
  • 2021-01-01 21:58

    I think the easiest way to achieve this is using Django password validation

    For minimum length would be enough adding this to settings file:

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
            'OPTIONS': {
                'min_length': 8,
            }
        },
    ]
    

    There are others validators like NumericPasswordValidator and CommonPasswordValidator

    0 讨论(0)
  • 2021-01-01 22:07

    Subclassing the user creation form sounds like a good approach. You can't enforce it at the database level, since Django only stores a hash of the password.

    0 讨论(0)
  • 2021-01-01 22:07

    Some info about answers,

    django.contrib.auth.password_validation.MinimumLengthValidator
    

    was newly implemented from django 1.9+ for older version it wont work,

    so you can go with your own custom validator,

    from django.core.exceptions import ValidationError
    from django.utils.translation import ugettext
    
    def validate(min_length, password):
        special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]"
        if len(password) < 8:
            raise ValidationError(ugettext('Password length must be greater than 8 character.'))
        if not any(char.isdigit() for char in password):
            raise ValidationError(ugettext('Password must contain at least %(min_length)d digit.') % {'min_length': min_length})
        if not any(char.isalpha() for char in password):
            raise ValidationError(ugettext('Password must contain at least %(min_length)d letter.') % {'min_length': min_length})
        if not any(char in special_characters for char in password):
            raise ValidationError(ugettext('Password must contain at least %(min_length)d special character.') % {'min_length': min_length})
    
    0 讨论(0)
提交回复
热议问题