我尝试自定义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
数据传递给PasswordResetView
和PasswordResetForm
,我没有找到明确的解决方案,因为用户数据是在创建PasswordResetForm
示例时使用的。
1条答案
按热度按时间nr7wwzry1#
SetPasswordForm
用于PasswordResetConfirmView
视图,而不是PasswordResetView
。在PasswordResetConfirmView
中,**get_form_kwargs()
**方法[Django-doc]被[GitHub]覆盖:因此,您可能应该子类化
PasswordResetConfirm
视图,并使用PasswordResetView
的PasswordResetForm
表单。