我無法覆蓋內置Django表單(django.contrib.auth.SetPasswordForm)的乾淨方法。該表單有兩個字段:new_password1和new_password2。覆蓋表單的乾淨方法來自定義錯誤消息
所以在我的views.py我所說的自定義表單(MySetPasswordForm
):
def reset_confirm(request, uidb64=None, token=None):
return password_reset_confirm_delegate(request,
template_name='app/reset_confirm.html',
set_password_form = MySetPasswordForm, uidb64=uidb64,
token=token, post_reset_redirect=reverse('main_page'))
在我forms.py:我想定義自己的清潔方法來顯示我的自定義錯誤消息。這裏就是我寫MySetPasswordForm
:
from django.contrib.auth.forms import SetPasswordForm
class MySetPasswordForm(SetPasswordForm):
error_messages = { 'password_mismatch': _("Missmatch!"), }
def clean(self):
password1 = self.cleaned_data.get('new_password1', '')
password2 = self.cleaned_data.get('new_password2', '')
print password1 #prints user's entered value
print password2 #prints nothing!!
print self.data['new_password2'] #prints user's entered value
if password1 == '':
self._errors["new_password1"] = ErrorList([u"enter pass1!"])
if password2 == '':
self._errors["new_password2"] = ErrorList([u"enter pass2"])
elif password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return self.cleaned_data
的問題是,當用戶輸入重複密碼錯誤,而不是讓"Missmatch" error
,它給"enter pass2"
!另外print password2
不會打印用戶輸入的password2密碼。
我在這段代碼中做錯了什麼?什麼是自定義錯誤消息的最佳方式?
p.s.在視圖中使用原始SetPasswordForm工作正常。
感謝您的回答,那麼如何設置'error_messages'字典呢? –
您已經在您的問題中設置了'error_messages'字典。我已經添加了一個例子。 – Alasdair
真棒tnx。猜猜我仍然是一個newby使用形式:) 我還需要在我的領域最小長度驗證,我可以做這個驗證使用error_messages(如果是如何?)或我必須使用乾淨的方法嗎? –