我正在尝试实施一个表单,让用户更改密码。
这里是代码:
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})
它不起作用,因为未定义用户。问题是如何将用户传递给表单。想法?感谢。
答案 0 :(得分:5)
只需将其作为save
方法的参数。
def save(self, user):
user.set_password(self.cleaned_data['password1'])
user.save()
...
form.save(request.user)
答案 1 :(得分:0)
用户可以从request.user
获取