首页 > 解决方案 > Django 管理员在发布后发送电子邮件

问题描述

所以我熟悉使用 django 发送电子邮件,但如果我使用管理面板而不是网站本身的管理面板,我想向所有订阅我的时事通讯的人发送一封电子邮件。我该怎么做呢?对于我当前对用户站点版本的看法,它类似于:

    def form_valid(self, form):
        message = 'A new article has been released...'
        subject = 'New Article!'
        to = Email.objects.values_list('email', flat=True).distinct()
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, message, from_email, to, fail_silently=True)

        return super().form_valid(form)

标签: pythondjango

解决方案


使用 django 信号将通过管理员或站点无关紧要。

You can create a signal in blog post view like this:

@receiver(post_save, sender=BlogPost)
def send_mail_to_subs(sender, instance, created, **kwargs):
    if created:
        for subs in instance.author.subscribed.all():
            send_mail(
                f'New Post from {instance.author}',
                f'Title: {instance.post_title}',
                'youremail',
                [subs.email],
            )

良好的编码:)


推荐阅读