为什么django内置auth视图无法识别自定义表单?

我知道当我们需要制作django内置视图时,应该在内置视图函数可以使用之前进行参数规范 .

现在我想自定义django auth视图的表单 password_reset_confirm

并在网址中,我导入我的自定义表单

from Myapp.forms import PasswordSetForm
from django.contrib.auth import urls,views

并为网址

url(r'^accounts/ ^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$  ',
        'django.contrib.auth.views.password_reset_confirm',{'set_password_form':PasswordSetForm},
        name='password_reset_confirm'),
url(r'^accounts/', include('django.contrib.auth.urls')),

在我的form.py我导入原始的 SetPasswordForm ,由django password_reset_confirm funciton用作默认格式

from django.contrib.auth.forms import SetPasswordForm

然后自定义表单

class PasswordSetForm(SetPasswordForm):
    error_messages = {
        'invalid_password': _("Please enter a valid password as instructed"),
        'password_mismatch': _("The two password fields didn't match."),
    }


    #new_password1 = forms.CharField(label=_("New password"),
    #                                widget=forms.PasswordInput)
    #new_password2 = forms.CharField(label=_("New password confirmation"),
    #                                widget=forms.PasswordInput)


    new_password1 = forms.CharField(widget=forms.PasswordInput, min_length=6, label='New Password' )
    new_password2 = forms.CharField(widget=forms.PasswordInput, min_length=6, label='Confirm new password')

    def clean_new_password1(self):
        new_password1 = self.cleaned_data.get("new_password1")

        # password must contain both Digits and Alphabets
        # password cannot contain other symbols
        if new_password1.isdigit() or new_password1.isalpha() or not new_password1.isalnum():
            raise forms.ValidationError(
                self.error_messages['invalid_password'],
                code='invalid_password',
            ) 
        return new_password1

正如您所看到的,对new_password1进行了更多检查

但尝试多次之后页面仍然使用默认的SetpasswordForm,因为两个密码的默认标签显示在我的html而不是我的自定义标签中(在html {{form.new_password2.label}} 用于显示标签)并且没有额外检查new_password1是DONE

我试图创建另一个不继承SetPassordForm并将其传递给 password_reset_confirm 的MyPasswordSetForm,但它没有任何区别,仍然使用默认表单 .

我已经google了很多,并就此提出问题,看来这是正确的方法,但这可能是什么问题?

非常感谢您的帮助 .

回答(1)

3 years ago

哎呀,那个URL regexp看错了错了:

r'^accounts/ ^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$  '

它应该是:

r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'