Reputation: 1736
I have an account settings page where a user can fill out his first/last name, username, email address, and phone number. I am also taking advantage of the PasswordChangeForm
provided by Django to let a user change their password with the same single form.
I would like to make it possible for a user to make changes to their personal details such as their email address or phone number without having to fill out the "old password," "new password," and repeat "new password". (For instance, the WordPress profile settings page works in this fashion.)
These three password fields should only be validated if one or more of them are not blank.
Doing the following in my views.py
still raises form errors for the password fields when one of the other fields has an error.
@sensitive_post_parameters()
@csrf_protect
@login_required
def account(request):
if request.method == "POST":
form1 = AccountDetailsForm(request.POST, instance=request.user)
form2 = AccountPhoneNumber(request.POST, instance=request.user.get_profile())
form3 = ChangePasswordForm(user=request.user, data=request.POST)
if form1.is_valid() and form2.is_valid():
if form3.has_changed():
if form3.is_valid():
form1.save()
form2.save()
form3.save()
messages.success(request, 'Accont Settings and Password Saved.')
return redirect('account')
else:
form1.save()
form2.save()
messages.success(request, 'Account Settings Saved.')
return redirect('account')
else:
form1 = AccountDetailsForm(instance=request.user)
form2 = AccountPhoneNumber(instance=request.user.get_profile())
form3 = ChangePasswordForm(user=request.user)
return render(request, 'account.html', locals())
Any tips? Thanks!
Upvotes: 0
Views: 1885
Reputation: 1736
Looks like I found an undocumented solution to my own question. Just need to add empty_permitted=True
as a parameter when defining the form as seen below:
form3 = ChangePasswordForm(user=request.user, data=request.POST, empty_permitted=True)
That immediately solves the problem with the code in the snippet I've provided in the original question.
Upvotes: 1