简体   繁体   English

django内置password_reset更改send_email的连接

[英]django built-in password_reset change connection from send_email

In my application i'm using the built-in auth views. 在我的应用程序中,我正在使用内置的身份验证视图。 I'm also using a postmark connection using django-anymail for some user email notifications. 我还将使用django-anymail的邮戳连接用于某些用户电子邮件通知。

Example: 

email_backend = get_connection('anymail.backends.postmark.EmailBackend')
   mail = EmailMessage(
   subject=subject,
   body=message,
   to=[settings.DEFAULT_FROM_EMAIL],
   connection=email_backend
   )

I want to change the connection i'm sending email with in PasswordResetView. 我想更改在PasswordResetView中发送电子邮件的连接。 Is there any way i can give a keyword argument in the PasswordResetView.as_view() the same way i'm giving html_email_template_name='...' or success_url='...' ? 有什么办法,我可以给在PasswordResetView.as_view关键字参数()以同样的方式,我给html_email_template_name='...'success_url='...' or do i have to rewrite PasswordResetView? 还是我必须重写PasswordResetView?

You don't have to change the PasswordResetView , but you will have to create a custom PasswordResetForm that you can then pass as a keyword argument to PasswordResetView.as_view() . 您不必更改PasswordResetView ,但必须创建一个自定义的PasswordResetForm ,然后可以将其作为关键字参数传递给PasswordResetView.as_view()

If you look at the source code of PasswordResetView , you will see that it doesn't actually send the email itself. 如果查看PasswordResetView的源代码,您会发现它实际上并不发送电子邮件本身。 The email sending is done as part of PasswordResetForm.save() , which calls PasswordResetForm.send_mail() 电子邮件发送是作为PasswordResetForm.save()一部分完成的,它调用了PasswordResetForm.send_mail()

You could subclass PasswordResetForm and overwrite .send_mail() to use your custom email backend: 您可以将PasswordResetForm子类化并覆盖.send_mail()以使用您的自定义电子邮件后端:

from django.contrib.auth.forms import PasswordResetForm

class PostmarkPasswordResetForm(PasswordResetForm):
    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email` using
        `anymail.backends.postmark.EmailBackend`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_backend = get_connection('anymail.backends.postmark.EmailBackend')

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email], connection=email_backend)
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM