Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Validate password with AUTH_PASSWORD_VALIDATORS

Tags:

python

django

I have a custom User model that only contains two mandatory fields: email and password.

I also have a custom UserCreationForm that prompts users for their email and one password.

Unfortunately, the form doesn't validate the password, aside from min_length.

How do I enable the password validators in settings.AUTH_PASSWORD_VALIDATORS? The object is a list of distc, not Validators, so I'm not sure how to use them.

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs=form_attrs.password),
        min_length=8,
        strip=True,
    )

    class Meta:
        model = User
        fields = ('email',)
        widgets = {
            'email': forms.EmailInput(attrs=form_attrs.email),
        }

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data.get('password1'))
        if commit:
            user.save()
        return user
like image 613
JayFresco Avatar asked Oct 28 '25 16:10

JayFresco


1 Answers

As another answerer mentioned, Django uses the django.contrib.auth.password_validation.validate_password method to validate the password. You can create a clean_password1 method and add this to it, like so:

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs=form_attrs.password),
        min_length=8,
        strip=True,
    )

    class Meta:
        model = User
        fields = ('email',)
        widgets = {
            'email': forms.EmailInput(attrs=form_attrs.email),
        }

    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        try:
            password_validation.validate_password(password1, self.instance)
        except forms.ValidationError as error:

            # Method inherited from BaseForm
            self.add_error('password1', error)
        return password1
like image 193
touch my body Avatar answered Oct 30 '25 06:10

touch my body