2012-07-27 34 views
5

Tôi muốn tạo biểu mẫu để đặt lại mật khẩu của người dùng. Cần lấy số current_password và sau đó là new_passwordconfirm_new_password. Tôi có thể thực hiện xác nhận để kiểm tra mật khẩu mới phù hợp. Làm cách nào để tôi có thể xác thực current_password? Có cách nào để vượt qua đối tượng User vào biểu mẫu không?Biểu mẫu Django + để đặt lại mật khẩu

Trả lời

6

Django có kèm theo PasswordChangeForm mà bạn có thể nhập và sử dụng trong chế độ xem của mình.

from django.contrib.auth.forms import PasswordChangeForm 

Nhưng bạn thậm chí không phải viết chế độ xem đặt lại mật khẩu của riêng mình. Có một cặp lượt xem django.contrib.with.views.password_changedjango.contrib.auth.views.password_change_done, bạn có thể móc thẳng vào cấu hình URL của mình.

+0

Vì mục đích của tôi, thao tác này sẽ không hoạt động. Vì tôi đang kết hợp đặt lại mật khẩu trong một biểu mẫu bao gồm nhiều thứ khác. Nhưng đây sẽ là cách chính xác cho trường hợp sử dụng này. – KVISH

+0

@KVISH Tôi biết đây là một nhận xét rất muộn nhưng đối với hồ sơ, bạn có thể hiển thị và xử lý nhiều hơn một biểu mẫu Django bên trong một HTML '

'. Có một vài lý do khiến bạn không thể sử dụng 'PasswordChangeForm' cùng với một biểu mẫu khác cho các thay đổi khác của bạn. – Oli

0

Tìm thấy một ví dụ thực sự tốt về điều này: http://djangosnippets.org/snippets/158/

[EDIT]

tôi đã sử dụng các liên kết ở trên và thực hiện một vài thay đổi. Họ đang ở đây bên dưới:

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') 
Các vấn đề liên quan