[Django]-How to use Django Password validation in my existing views?

3👍

You need to use forms to use those validators cleanly. Although you need to change those as well.

def min_length(password):  # validator
    if not re.findall('\d', password):
        raise ValidationError(
            _("The password must contain at least %(min_digits)d digit(s), 0-9."),
            code='password_no_number',
        )

Then update the form:

# in forms

class UserForm(forms.Form): 
  password = forms.CharField(widget=forms.PasswordInput(),validators=[min_length])

But, if don’t want to use django forms, then you need to run those validation manually, for example:

def register(request):
    validators = [MinimumLengthValidator, NumberValidator, UppercaseValidator]
    if request.method == 'POST':
       # some code
       password = request.POST('password')
       try:
           for validator in validators:
                validator().validate(password)
       except ValidationError as e:
           messages.error(request, str(e))
           return redirect('register')
👤ruddra

Leave a comment