Skip to main content
 首页 » 编程设计

python之Django-Notification之电子邮件后端的替代方案

2025年05月04日28zengkefu

我正在使用 Django 构建一个项目,目前正在尝试实现 django-notification 作为跟踪用户事件的一种方式。虽然我设法安装它并创建了一些通知,但它们仅通过电子邮件发送,而没有存储在相应的数据库中,以便我可以在提要 View 中显示它们。

/notifications/feed/目前给我一个类型错误,我不确定这是否相关?

在/notifications/feed/处出现类型错误 init() 恰好接受 3 个参数(给定 1 个)

如有任何建议,我们将不胜感激。我研究了 Pinax 如何使用通知,但无法弄清楚它们是如何超越仅电子邮件后端的。

在 settings.py 中,我启用了“通知”以及 template_context_processor“notification.context_processors.notification”。

网址.py

    url(r'^note/', include('notification.urls')), 

应用/管理.py

if "notification" in settings.INSTALLED_APPS: 
from notification import models as notification 
 
def create_notice_types(app, created_models, verbosity, **kwargs): 
    notification.create_notice_type("messages_received", _("Message Received"), _("you have received a message"), default=2) 
 
signals.post_syncdb.connect(create_notice_types, sender=notification) 

应用程序/view.py

...       
if notification: 
    notification.send([user], "messages_received", {'message': message,}) 
... 

notification.send 已执行,我检查了这个,但似乎“通知”数据库中没有存储任何内容..

我应该补充一点,我正在运行 django-notification ( https://github.com/brosner/django-notification ) 的 Brian Rosner 分支。

请您参考如下方法:

看来 brosner 的 django-notifications 分支与 jtauber 的不同之处在于 send_now() 实际上并没有将 Notice 实例添加到数据库中,默认的 EmailBackend 通知也没有后端。

您必须编写自己的通知后端类,在调用 deliver() 时创建一个 Notice 实例,并将其添加到 NOTIIFICATION_BACKENDS。

复制 jtauber 行为的(未经测试的)示例:

class MyBackend(BaseBackend): 
    def deliver(self, recepient, sender, notice_type, extra_context): 
        messages = self.get_formatted_messages(["notice.html"], 
            notice_type.label, extra_context) 
        notice = Notice.objects.create(recipient=recepient,   
            message=messages['notice.html'], notice_type=notice_type,  
            on_site=on_site, sender=sender) 
        notice.save()