2012-07-27 67 views
5

我想創建一個用於重置用戶密碼的表單。它應該採取current_password,然後new_passwordconfirm_new_password。我可以通過驗證來檢查新密碼是否匹配。我將如何驗證current_password?有沒有辦法將User對象傳遞給表單?用於重置密碼的Django +表單

回答

6

Django帶有一個內置的PasswordChangeForm您可以導入並在您的視圖中使用。

from django.contrib.auth.forms import PasswordChangeForm 

但是,你甚至不必編寫自己的密碼重置視圖。有一對視圖django.contrib.with.views.password_changedjango.contrib.auth.views.password_change_done,你可以直接進入你的URL配置。

+0

對我而言,這是行不通的。由於我在包含許多其他事物的表單中組合了密碼重置。但這將是這種用例的正確方法。 – KVISH 2012-07-27 01:31:24

+0

@KVISH我知道這是一個非常晚的評論,但爲了記錄,您可以在HTML'

'內顯示和處理多個Django表單。有幾個原因讓你無法將'PasswordChangeForm'與另一個表單一起用於其他更改。 – Oli 2014-12-31 08:14:35

0

實測值的這一個很好的例子:http://djangosnippets.org/snippets/158/

[編輯]

我用上述鏈接,並提出了一些變化。他們在這裏如下:

class PasswordForm(forms.Form): 
    password = forms.CharField(widget=forms.PasswordInput, required=False) 
    confirm_password = forms.CharField(widget=forms.PasswordInput, required=False) 
    current_password = forms.CharField(widget=forms.PasswordInput, required=False) 

    def __init__(self, user, *args, **kwargs): 
     self.user = user 
     super(PasswordForm, self).__init__(*args, **kwargs) 

    def clean_current_password(self): 
     # If the user entered the current password, make sure it's right 
     if self.cleaned_data['current_password'] and not self.user.check_password(self.cleaned_data['current_password']): 
      raise ValidationError('This is not your current password. Please try again.') 

     # If the user entered the current password, make sure they entered the new passwords as well 
     if self.cleaned_data['current_password'] and not (self.cleaned_data['password'] or self.cleaned_data['confirm_password']): 
      raise ValidationError('Please enter a new password and a confirmation to update.') 

     return self.cleaned_data['current_password'] 

    def clean_confirm_password(self): 
     # Make sure the new password and confirmation match 
     password1 = self.cleaned_data.get('password') 
     password2 = self.cleaned_data.get('confirm_password') 

     if password1 != password2: 
      raise forms.ValidationError("Your passwords didn't match. Please try again.") 

     return self.cleaned_data.get('confirm_password')