3
votes

I am using the Django native password reset functionality to reset account passwords.

urls.py

path('reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html',
                                                        form_class=PasswordResetform), name='reset'),
    path('reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='account/reset_done.html'),
         name='password_reset_done'),
    path("reset/<uidb64>/<token>/",
         auth_views.PasswordResetConfirmView.as_view(template_name='account/reset_confirm.html',
                                                     form_class=PasswordResetConfirm), name='password_reset_confirm'),
    path("reset/complete", auth_views.PasswordResetCompleteView.as_view(template_name='account/reset_complete.html'),
         name='password_reset_complete'),

now everything works fine, I get the password reset link in my email and when I open it I am able to reset my password, but after the user resets the password, I want to send them an email saying their password has been reset

I tried to write an ajax function that is triggered when it goes to the 'password_reset_complete' template, but there I am unable to access the user's email or username. how do i retrieve the user's email or username in the 3rd or the 4th template of the password reset steps?

1
Consider customizing PasswordResetCompleteView to extend it so that you can send emails to user upon successful password resetMuteshi

1 Answers

1
votes

I think the easiest way is to subclass the SetPasswordForm:

from django.contrib.auth.forms import SetPasswordForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import get_user_model

UserModel = get_user_model()

class MySetPasswordForm(SetPasswordForm):

    def send_email(self, to_mail):
        subject = 'Password changed successfully'
        body = 'Your password has been changed successfully'
        email = EmailMultiAlternatives(subject, body, None, [to_email])
        email.send()
    
    def save(self, commit=True):
        if commit:
            email = email_field_name = UserModel.get_email_field_name()
            user_email = getattr(self.user, email_field_name)
            self.send_email(user_email)
        super().save_(commit=commit)

and then use this form:

path(
    'reset/complete',
    auth_views.PasswordResetCompleteView.as_view(
        template_name='account/reset_complete.html',
        form_class=MySetPasswordForm
    ),
    name='password_reset_complete'
),