2015-08-22 101 views
1

我想在Django上設置SetPasswordForm,但是在嘗試輸入新密碼時出現以下錯誤:'SetPasswordForm' object has no attribute ‘save’'SetPasswordForm'對象沒有'保存'屬性 - Django

有誰知道如何正確配置它?先謝謝你!

forms.py:

class SetPasswordForm(forms.Form): 
    password1 = forms.CharField(label='New password', 
           widget=forms.PasswordInput(
            attrs={'placeholder': 'New password'})) 
    password2 = forms.CharField(label='Verify', 
           widget=forms.PasswordInput(
            attrs={'placeholder': 'Password again'})) 

    def __init__(self, *args, **kwargs): 
     self.user = kwargs.pop('user') 
     super(SetPasswordForm, self).__init__(*args, **kwargs) 

    def clean_password2(self): 
     password_length = settings.MIN_PASSWORD_LENGTH 
     password1 = self.cleaned_data.get("password1") 
     if len(password1) < password_length: 
      raise forms.ValidationError(
       "Password must be longer than " 
       "{} characters".format(password_length)) 
     password2 = self.cleaned_data.get("password2") 
     if password1 and password2: 
      if password1 != password2: 
       raise forms.ValidationError("Passwords do not match") 
     return password2 

views.py:

@sensitive_post_parameters() 
@never_cache 
def password_reset_confirm(request, uidb64=None, token=None, 
          token_generator=default_token_generator): 
    assert uidb64 is not None and token is not None 
    try: 
     uid = force_text(urlsafe_base64_decode(uidb64)) 
     user = MyUser._default_manager.get(pk=uid) 
    except (TypeError, ValueError, OverflowError, MyUser.DoesNotExist): 
     user = None 

    if user is not None and token_generator.check_token(user, token): 
     validlink = True 
     form = SetPasswordForm(request.POST or None, user=user) 
     if request.method == 'POST': 
      if form.is_valid(): 
       form.save() # Error traces back to here 
       return HttpResponseRedirect(render("login")) 
    else: 
     validlink = False 
     form = None 
     messages.error(request, "Password reset unsuccessful") 
    context = { 
     'form': form, 
     'validlink': validlink 
    } 
    return render(request, 'accounts/settings/password_set.html', context) 

回答

0

我只需要添加以下到我的表格:

def save(self, commit=True): 
    self.user.set_password(self.cleaned_data['password2']) 
    if commit: 
     self.user.save() 
    return self.user 
相關問題