【问题标题】:Send email to user after password reset in django在 django 中重置密码后向用户发送电子邮件
【发布时间】:2021-03-08 06:37:41
【问题描述】:

我正在使用 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 以扩展它,以便您可以在密码重置成功后向用户发送电子邮件

标签: django django-views django-forms django-templates


【解决方案1】:

我认为最简单的方法是继承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)

然后使用这种形式:

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

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2013-12-18
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2015-03-12
    • 2021-08-05
    • 2012-06-15
    • 2011-02-08
    相关资源
    最近更新 更多