在Django中重置密码后向用户发送电子邮件

4

我使用Django的原生密码重置功能来重置账户密码。

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'),

现在一切运作良好,我已经收到了重置密码的链接,并且当我打开它时可以成功重置我的密码。但是在用户重置密码后,我想给他们发送一封邮件,告诉他们他们的密码已被重置

我尝试编写一个ajax函数,在“password_reset_complete”模板上触发,但是我无法访问用户的电子邮件或用户名。如何在密码重置步骤的第三或第四个模板中检索用户的电子邮件或用户名?


考虑自定义 PasswordResetCompleteView 以扩展它,以便在成功重置密码后向用户发送电子邮件。 - Muteshi
1个回答

3

我认为最简单的方法是对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 <b>send_email</b>(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.<b>send_email(user_email)</b>
        super().save_(commit=commit)

然后使用这个表单:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接