0

I have the following view for my page to reset your password:

from django.contrib.auth.forms import PasswordChangeForm

def password_change(request):

    if request.method == 'POST':
        password_form = PasswordChangeForm(data=request.POST, user=request.user)
        if password_form.is_valid():
            password_form.save()
            update_session_auth_hash(request, password_form.user)
            messages.add_message(request, messages.SUCCESS, "Password reset.")
            return redirect(reverse('elections:home'))
        else:
            messages.add_message(request, messages.ERROR, "Error with password reset.")
            return redirect('/password/new/')
    else:
        password_form = PasswordChangeForm(user=request.user)

    return render(request, 'registration/password_change.html', {
        'form': password_form
    })

Some of my users are reporting that they are unable to change their password, but it is working for me. As I can't ask them what their password is for obvious reasons, I need a more informative error feedback to the user.

It is my understanding that PasswordChangeForm generates errors that I can access. Is this true, and if so how do I access these errors in the view to add them to the Django message? If not, how do I create my own form that will return these errors?

cbuch1800
  • 923
  • 3
  • 11
  • 26

2 Answers2

0

Django form field entries that fail validation raise ValidationError exception(s), so you could do something like (Django 2.0):

try:
    if password_form.is_valid():
        password_form.save() # etc...
except ValidationError as e:
    messages.error(request, e)
Rob Simpson
  • 356
  • 3
  • 6
-1

You should be able to just render the form errors in your template. Provided that when the password is invalid you just load the page with the filled form. You can do that by removing the else after form.is_valid():

password_form = PasswordChangeForm(data=request.POST, user=request.user)
if password_form.is_valid():
    ...
else: #remove the else block here so that the filled form is rendered when there is an error

Making sure you that if you are rendering the form manually you have included the proper error tags as described here: https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually

hwhite4
  • 695
  • 4
  • 6
  • I don't want to do this, I want to refer to and access the error in the view so that I can display it using a message in keeping with every other alert in my website. Do you know how to do this? – cbuch1800 Mar 04 '18 at 12:11
  • 1
    In the view you can access the errors using form.errors which returns a dictionary – hwhite4 Mar 05 '18 at 07:27
  • 1
    It's explained in the docs here https://docs.djangoproject.com/en/2.0/ref/forms/api/#django.forms.Form.errors – hwhite4 Mar 05 '18 at 07:28