使用 UserAttributeSimilarityValidator 和 CustomUser Django 进行密码验证

Password validation with UserAttributeSimilarityValidator and CustomUser Django

我正在尝试根据 CustomUser 字段验证密码: 电子邮件和 full_name.

除了 UserAttributeSimilarityValidator 之外的所有测试验证都有效,这是我在下面的代码中包含的唯一测试。

forms.py

    class RegistrationForm(forms.ModelForm):
        email = forms.EmailField(label=_('Email address'),
                                 widget=forms.EmailInput(attrs={'class': 'form-control mb-4',
                                                            'class': 'form-control mb-4',
                                                            }))

        full_name = forms.CharField(label=_('Full name'),
                                    widget=forms.TextInput(attrs={'class': 'form-control mb-4',
                                                              }))
        password = forms.CharField(label=_('Password'),
                                   widget=forms.PasswordInput(attrs={'class': 'form-control mb-4',
                                                                 'autocomplete': 'new-password',
                                                                 'id': 'psw',
                                                                 }))

        class Meta:
            model = get_user_model()
            fields = ('full_name', 'email', 'password')

        def clean_password(self):
            password = self.cleaned_data.get("password")
            if password:
                try:
                    password_validation.validate_password(password, self.instance)
                except ValidationError as error:
                    self.add_error("password", error)
            return password

        def clean_email(self):
            email = self.cleaned_data['email']
            if User.objects.filter(email=email).exists():
                raise forms.ValidationError(
                mark_safe(_(f'A user with that email already exists, click this <br><a href="{reverse("account:pwdreset")}">Password Reset</a> link'
                      ' to recover your account.'))
            )

            return email

tests.py

@override_settings(
        AUTH_PASSWORD_VALIDATORS=[
            {
                'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
                'OPTIONS': {
                    'user_attributes': (
                            'email', 'full_name',
                    )},
            },

        ]
    )
    def test_validates_password(self):
        data = {
            "email": "jsmith@example.com",
            "full_name": "John Smith",
            "password": "jsmith",
        }
        form = RegistrationForm(data)
        self.assertFalse(form.is_valid()
        self.assertEqual(len(form["password"].errors), 1)

        self.assertIn(
            "The password is too similar to the email.",
            form["password"].errors,
        )

由此产生的测试结果:

FAIL: test_validates_password (account.tests.test_forms.RegistrationFormTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/tester/Documents/dev/test/venv/lib/python3.8/site-packages/django/test/utils.py", line 437, in inner
    return func(*args, **kwargs)
  File "/Users/tester/Documents/dev/test/account/tests/test_forms.py", line 112, in test_validates_password
    self.assertFalse(form.is_valid())
AssertionError: True is not false

----------------------------------------------------------------------
Ran 5 tests in 0.868s

FAILED (failures=1)
Destroying test database for alias 'default'...

这是完全合乎逻辑的,因为 UserAttributeSimilarityValidator 没有获取电子邮件和密码字段之间的相似性。

拜托,我做错了什么?

    Django 4.0.2

解决方案是从django.contrib.auth.forms.UserCreationForm复制save()方法并添加到表单中:

def save(self, commit=True):
      """
      Save user.
      Save the provided password in hashed format.
      :return custom_user.models.EmailUser: user
      """
      user = super().save(commit=False)
      user.set_password(self.cleaned_data["password"])

     if commit:
            user.save()
     return user