0

我正在尝试为知道密码并可以登录但想要更改密码的用户制作更改密码表单。我制作了一个表单和一些东西,但它似乎没有将用户对象传递到表单中,因为它说它是一个 NoneType 对象。

#forms.py
class ChangePasswordForm(forms.Form):
    error_messages = {
        'wrong_current': _("You did not enter the right password!"),
        'invalid_new': _("You have entered an invalid new password or you did not enter one!"),
        'no_match': _("The new passwords do not match!")
    }
    current_password = forms.CharField(widget=forms.PasswordInput)
    new_password1 = forms.CharField(widget=forms.PasswordInput, label="New Password: ")
    new_password2 = forms.CharField(widget=forms.PasswordInput, label="Repeat New Password: ")

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

    def clean(self):
        try:
            a = u.objects.get(username__iexact=self.user)
        except u.DoesNotExist:
            pass
        if self.cleaned_data['new_password1'] != self.cleaned_data['new_password2']:
            raise forms.ValidationError(self.error_messages['no_match'])
        if a.check_password(self.cleaned_data["current_password"]) == "False":
            raise forms.ValidationError(self.error_messages["wrong_current"])
        return self.cleaned_data
#views.py
def change_pass_view(request):
    if request.method =="POST":
        form = ChangePasswordForm(request.POST)
        if form.is_valid():
            user = u.objects.get(username__iexact=request.user)
            user.set_password(form.cleaned_data["new_password1"])
            user.save()
        else:
            print "invalid"
            a = request.user
            a = u.objects.get(username__iexact=a)
            form = UserModificationForm(instance=a)
            form2 = ChangeEmailForm()
            form3 = ChangePasswordForm(user=request.user)
            return render(request, 'accounts/modify.html', {'form': form, 'form2': form2, 'form3': form3, 'usr':request.user, 'email':request.user.email})
    else:
        return redirect('/')    

我非常需要一些帮助!

4

1 回答 1

0

我找到了答案。我不知道在 django 中已经有我想要的预制表格。它现在完美运行。

于 2013-08-21T22:11:20.577 回答