Skip to main content
 首页 » 编程设计

python之Django-如何让django内置的auth View 识别自定义表单

2024年11月01日35开发

我正在使用 django 内置的 auth url 和 View

所以,在 url.py 中

url(r'^accounts/', include('django.contrib.auth.urls')), 

在 views.py 中

from MyApp.forms import * 
from django.contrib.auth.views import * 

我想自定义 django inbuit viewpassword_reset_confirm 函数使用的 SetPasswordForm,因为我需要用 new_password1 做更多检查

在我的 forms.py 中,我有如下自定义的 SetPasswordForm(已经从 contrib.auth.forms 导入了 SetPasswordForm

class SetPasswordForm(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(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): 
        password1 = self.cleaned_data.get("password1") 
 
        # password must contain both Digits and Alphabets 
        # password cannot contain other symbols 
        if password1.isdigit() or password1.isalpha() or not password1.isalnum(): 
            raise forms.ValidationError( 
                self.error_messages['invalid_password'], 
                code='invalid_password', 
            )  
        return password1 

谁能帮助解释为什么 django 内置 View 无法识别我自定义的 SetPasswordForm 以及是否可以这样做?

如果不是要识别自定义的 SetPasswordForm,那就意味着我必须重新定义 url 和 View 参数(以指定要使用的表单),对吗?如果有任何错误,请纠正我

非常感谢。

请您参考如下方法:

您应该覆盖 URL 以将您的自定义表单类作为 View 关键字参数传递。详见How to override a view from an external Django app .