Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active October 8, 2017 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LowerDeez/f0428d9cc7e4d75188765fa65fc46681 to your computer and use it in GitHub Desktop.
Save LowerDeez/f0428d9cc7e4d75188765fa65fc46681 to your computer and use it in GitHub Desktop.
Django. Extend PasswordResetForm to check for email in database.
from django.contrib.auth.forms import PasswordResetForm
class MailCheckPasswordResetForm(PasswordResetForm):
email = forms.EmailField(max_length=254)
error_messages = {
'unknown': _("That email address doesn't have an associated "
"user account. Are you sure you've registered?"),
'unusable': _("The user account associated with this email "
"address cannot reset the password."),
}
def clean_email(self):
"""
Validates that an active user exists with the given email address.
"""
email = self.cleaned_data["email"]
self.users_cache = get_user_model()._default_manager.filter(email__iexact=email)
if not len(self.users_cache):
raise forms.ValidationError(self.error_messages['unknown'])
if not any(user.is_active for user in self.users_cache):
# none of the filtered users are active
raise forms.ValidationError(self.error_messages['unknown'])
if any((user.password == user.set_unusable_password())
for user in self.users_cache):
raise forms.ValidationError(self.error_messages['unusable'])
return email
url(r'^password_reset/$', auth_views.password_reset,
{'template_name': 'accounts/password_reset/password_reset.html',
'email_template_name': 'accounts/password_reset/password_reset_email.html',
'post_reset_redirect': 'account:password_reset_done',
'password_reset_form': PasswordResetForm}, # <---
name='password_reset'),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment