Django中的表单问题

时间:2011-05-10 21:21:27

标签: python django django-forms

我正在尝试实施一个表单,让用户更改密码。

这里是代码:

forms.py

class ChangePasswordForm(forms.Form):
    password1 = forms.CharField(widget = forms.PasswordInput(), required = True)
    password2 = forms.CharField(widget = forms.PasswordInput(), required = True)

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError("The two password fields didn't match.")
        return password2

    def save(self, *args, **kw):
        self.user.set_password(self.cleaned_data['password1'])
        print "Pass setted."
        self.user.save()

views.py

def change_password(request):
    form = ChangePasswordForm()
    if request.method == 'POST':
        form = ChangePasswordForm(request.POST, instance = request.user)
        if form.is_valid():
            password1 = form.cleaned_data['password1'];
            password2 = form.cleaned_data['password2'];
            print password1 + " == " + password2
            form.save()
            messages.success(request, "Password updated!")
            return HttpResponseRedirect('')

    return render(request, 'change_password.html', {'form': form})

它不起作用,因为未定义用户。问题是如何将用户传递给表单。想法?感谢。

2 个答案:

答案 0 :(得分:5)

只需将其作为save方法的参数。

def save(self, user):
    user.set_password(self.cleaned_data['password1'])
    user.save()

...


form.save(request.user)

答案 1 :(得分:0)

用户可以从request.user获取