Sarp
Sarp

Reputation: 55

Django password_reset Form email validation

Django password_reset Form does not check if email exists or not. Also validates form whatever email address is given.

The question is, how do i check and throw error for non existing emails with custom form?

By the way, i found below solution at here but it is not working for me. (using Django 2.1). And if this should work, i couldn't found what i am missing.

forms.py

class EmailValidationOnForgotPassword(PasswordResetForm):
def clean_email(self):
    email = self.cleaned_data['email']
    if not User.objects.filter(email__iexact=email, is_active=True).exists():
        raise ValidationError("There is no user registered with the specified email address!")

    return email

urls.py

path('sifre-sifirla/', PasswordResetView.as_view(), {'password_reset_form':EmailValidationOnForgotPassword}, name='password_reset'),

Thank you in advance.

EDIT:

For other users information, question is answered by @Alasdair and working but @pypypy 's point of view is also important.

changes in urls.py as below:

path('sifre-sifirla/', PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'),

Upvotes: 3

Views: 1369

Answers (1)

ohlr
ohlr

Reputation: 1909

Summarizing the discussion above with parts taken from @Alasdair

#forms.py
from django.contrib.auth.forms import PasswordResetForm

class EmailValidationOnForgotPassword(PasswordResetForm):

    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email__iexact=email, is_active=True).exists():
            msg = _("There is no user registered with the specified E-Mail address.")
            self.add_error('email', msg)
        return email

And

#urls.py
from accounts.forms import EmailValidationOnForgotPassword

path('sifre-sifirla/', PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'),

@pypypy, is correct in saying that this approach can be used to obtain usernames. One way to reduce this issue is to respond with a 429 Too Many Requests as soon an user tries 3 different E-Mails. That can be achived using for example django-ratelimit

Upvotes: 1

Related Questions