0

I am having issues trying to displaying error messages on different authentication forms

  1. On password reset form: What I am trying to achieve is to display error message like "Email not in our database" when a user enters unregistered email.
  2. on password set form: I am trying to display "New Passwords and Confirm Passwords not matching" and any other messages pertaining to the form

Below are my codes

on forms.py

from django.contrib.auth.forms import PasswordResetForm

class PasswordReset(PasswordResetForm):
    email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Email'}))

class SetPassword(SetPasswordForm):
    new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control form-control-lg', 'placeholder':'New Password'}))
    new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Confirm Password'}))

on urls.py

urlpatterns = [
 path(
        'reset-password/',
        auth_views.PasswordResetView.as_view(template_name='backend/reset-password.html', 
        email_template_name='backend/password-reset-email.html', form_class=PasswordReset), name='password_reset'
     ),

 path(
        'password-reset/<uidb64>/<token>/',
        auth_views.PasswordResetConfirmView.as_view(template_name='backend/password-confirm-form.html',
        form_class=SetPassword), name='password_reset_confirm'
     ),
]

on reset-password.html

<form class="pt-3" method="post">
    {% if form.errors %}
    <div class="alert alert-danger">{{ form.errors }}</div>
    {% endif %}
    <div class="form-group">
      {{ form.email }}
    </div>
    <input type='submit' value='Reset Password'>
</form> 

on password-confirm-form.html

<form method="post">
{% if form.errors %}
    <div class="alert alert-danger">{{ form.errors }}</div>
{% endif %}
<div class="form-group">
      {{ form.new_password1  }}
</div>
<div class="form-group">
      {{ form.new_password2 }}
</div>
<input type="submit" value="Change Password">
</form> 
kennyb
  • 11
  • 4

1 Answers1

0

You need to update few things in the form. For SetPassword:

class SetPassword(SetPasswordForm):
    error_messages = {
        'password_mismatch': _('New Passwords and Confirm Passwords not matching'),
    }

And in ResetPassword form:

class PasswordReset(PasswordResetForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email = email).exists():
            raise ValidationError('Email not in our database')
        return email
Moha369
  • 815
  • 7
  • 16
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • return `email`*, `User.objects.filter(email = email)`* – Moha369 Jan 17 '20 at 03:54
  • Thanks @ruddra, is there not better way? instead of writting extra code on forms.py? Is the problem from the way the messages are being rendered on the template ? – kennyb Jan 17 '20 at 04:24