Django自定义密码重置视图:__init__()缺少1个必需的位置参数:'user'

nwwlzxa7  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(90)

我尝试自定义Django PasswordResetView来验证密码的长度,但我得到了这个错误:

TypeError at /accounts/password_reset/
__init__() missing 1 required positional argument: 'user'

views.py

from django.contrib.auth import views as auth_views

class PasswordResetView(auth_views.PasswordResetView):
    form_class = PasswordResetForm
    template_name = "accounts/users/password_reset.html"
    email_template_name = "accounts/users/password_reset_email.html"
    subject_template_name = "accounts/users/password_reset_subject.txt"
    from_email = settings.EMAIL_HOST_USER
    success_url = reverse_lazy("accounts_password_reset_done")

forms.py

from django.contrib.auth.forms import SetPasswordForm

class PasswordResetForm(SetPasswordForm):

    def clean_new_password1(self):
        password = self.cleaned_data.get("new_password1")
        if len(password) < 12:
            raise forms.ValidationError("Password must be at least 12 characters.")
        return password

很明显,SetPasswordForm类需要在初始化时被用户接受:

class SetPasswordForm(forms.Form):
   . . .
    
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super().__init__(*args, **kwargs)

对于如何将user数据传递给PasswordResetViewPasswordResetForm,我没有找到明确的解决方案,因为用户数据是在创建PasswordResetForm示例时使用的。

nr7wwzry

nr7wwzry1#

SetPasswordForm用于PasswordResetConfirmView视图,而不是PasswordResetView。在PasswordResetConfirmView中,**get_form_kwargs()**方法[Django-doc]被[GitHub]覆盖:

def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['user'] = self.user
    return kwargs

因此,您可能应该子类化PasswordResetConfirm视图,并使用PasswordResetViewPasswordResetForm表单。

相关问题