2012-07-27 14 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

+0

@KVISHこれは非常に遅いコメントですが、レコードのために、複数のDjangoフォームをHTMLの '

'の中に表示して処理することができます。他の変更のために 'PasswordChangeForm'を別のフォームと一緒に使うことができない理由はほとんどありません。 – Oli

0

http://djangosnippets.org/snippets/158/

を[EDIT]

私は、上記のリンクを使用して、いくつかの変更を加えました。彼らはここに下記のとおりです。

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') 
関連する問題