【问题标题】:Sending email notifications to subscribers when new blog post is published in Wagtail在 Wagtail 中发布新博客文章时向订阅者发送电子邮件通知
【发布时间】:2020-07-06 16:34:53
【问题描述】:

我正在将现有的 Django 项目转换为 Wagtail。我遇到的一个问题是电子邮件通知。在 Django 项目中,我可以让人们订阅博客,并且每当发布新帖子时,作者都可以手动向管理员中的所有订阅者发送通知。但是,我不确定如何在 Wagtail 中完成此操作。

我已阅读有关 page_published 信号 (https://docs.wagtail.io/en/stable/reference/signals.html#page-published) 的文档,但是,我不确定如何将当前代码集成到其中。此外,我希望作者手动发送通知,因为作者不想在每次编辑和发布博客文章时都向订阅者发送电子邮件。

作为参考,我对 Django 应用程序的当前代码如下(仅当博客应用程序在普通 Django 中时才有效;因为博客模型现在在 Wagtail 应用程序中,当前代码不再有效)。

models.py

class Post(models.Model):
    """Fields removed here for brevity."""
    ...
    def send(self, request):
        subscribers = Subscriber.objects.filter(confirmed=True)
        sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
        for sub in subscribers:
            message = Mail(
                    from_email=settings.FROM_EMAIL,
                    to_emails=sub.email,
                    subject="New blog post!",
                    html_content=(               #Abbreviated content here for brevity
                        'Click the following link to read the new post:' \
                        '<a href="{}/{}/">{}</a>'\
                        'Or, you can copy and paste the following url into your browser:' \
                        '{}/{}'\
                        '<hr>If you no longer wish to receive our blog updates, you can ' \
                        '<a href="{}/?email={}&conf_num={}">unsubscribe</a>.').format(
                            request.build_absolute_uri('/post'),
                            self.slug,
                            self.title,
                            request.build_absolute_uri('/post'),
                            self.slug,
                            request.build_absolute_uri('/delete'),
                            sub.email,
                            sub.conf_num
                        )
                    )
            sg.send(message)

admin.py

def send_notification(modeladmin, request, queryset):
    for post in queryset:
        post.send(request)

send_notification.short_description = "Send selected Post(s) to all subscribers"

@admin.register(Post)
class PostAdmin(SummernoteModelAdmin):
    ...
    actions = [send_notification]

任何建议或反馈将不胜感激!提前致谢!

编辑 1

Wagtail Slack 建议我使用 register_page_action_menu_item 钩子 (https://docs.wagtail.io/en/stable/reference/hooks.html?highlight=hooks#register-page-action-menu-item)。我在 Wagtail 的页面编辑器上成功实现了操作菜单项,但是我无法执行我的电子邮件方法(可能是因为我不知道如何正确使用钩子)。以下是我的wagtail_hooks.py 文件中的代码。

from wagtail.admin.action_menu import ActionMenuItem
from wagtail.core import hooks

from .models import Subscriber
from django.conf import settings
from django.core.mail import send_mail
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

class NotificationMenuItem(ActionMenuItem):
    name = 'email-notification'
    label = "Notify Subscribers of New Post"

    def send(self, request):
    """Used the same def send() method here from my models.py above"""

@hooks.register('register_page_action_menu_item')
def register_notification_menu_item():
    return NotificationMenuItem(order=100)

如果有人对如何修复它以使其执行有任何建议,请告诉我!

编辑 2

更多问题! (虽然我觉得我越来越近了。)

wagtail_hooks.py 修改为以下内容,我可以发送电子邮件,但是在页面加载时发生。所以每次我在编辑器中加载博客文章时,它都会发送一封电子邮件。单击我创建的操作菜单项会触发页面重新加载,然后会发送另一封电子邮件(所以我认为我的操作菜单项在单击时实际上不起作用)。

另一个问题:因为我将send() 方法移到NotificationMenuItem 类中,我无法在电子邮件的url 中动态生成博客文章的标题和标题。

wagtail_hooks.py

class NotificationMenuItem(ActionMenuItem):
    name = 'email-notification'
    label = "Notify Subscribers of New Post"

    def send(self, request):
    """Used the same def send() method here from my models.py above"""

    def get_url(self, request, context):
        self.send(request)

编辑 3

尽管模型是 Wagtail 模型,但我设法让通知系统在常规 Django 管理员中工作。虽然这会将当前网站的功能转移到新的 wagtail 网站,但我仍然无法解决编辑 2 中提出的最新问题。

这是管理员中的新代码:

def send_notification(modeladmin, request, queryset):
    for post in queryset:
        post.send(request)

send_notification.short_description = "Send selected Post(s) to all subscribers"

class BlogPageAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'body')
    search_fields = ['title', 'body']
    actions = [send_notification]
admin.site.register(BlogPage, BlogPageAdmin)

【问题讨论】:

    标签: django wagtail email-notifications


    【解决方案1】:

    最好使用 post_save 信号。

    @receiver(post_save, sender=BlogPost)
    def send_mail_to_subs(sender, instance, created, **kwargs):
        current_site = Site.objects.get_current()
        domain = current_site.domain
        if created:
            for subs in instance.author.subscribed.all():
                send_mail(
                    f'New Post from {instance.author}',
                    f'Title: {instance.post_title}\nContent: {instance.post_content}\nDate Created: {instance.created}\nUrl: {domain}',
                    'youremail',
                    [subs.email],
            )
    

    良好的编码。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2010-11-01
      • 2018-01-09
      • 2016-02-18
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2017-08-08
      • 2021-08-21
      相关资源
      最近更新 更多