Reputation: 5010
I'm trying to implement a form for let the user change their password.
Here the code:
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})
It doesn't work because user is not defined. The problem is how to pass user to the form. Ideas? Thanks.
Upvotes: 2
Views: 195
Reputation: 599630
Just make it a parameter to the save
method.
def save(self, user):
user.set_password(self.cleaned_data['password1'])
user.save()
...
form.save(request.user)
Upvotes: 5