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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With