当管理员向用户添加通知时,我有一个用户通知我想在用户的主页上显示,如 facebook 喜欢或事件提要是否可以使用 django ?
模型.py
class Notification(BaseModel):
created_user = models.ForeignKey(User)
title = models.CharField(max_length=225)
description = models.TextField(max_length=600)
is_read = models.BooleanField(default=False)
priority = models.CharField(max_length=20, choices=NOTIFICATION_STATUS, default=LOW)
def __str__(self):
return self.title
我可以添加新的通知,但在用户刷新页面时会列出通知。只是我只想像 facebook 这样的系统一样异步执行此操作。
最佳答案
Channels
是此用例的最佳解决方案。它是 websocket 和真正的异步,并实时连接您的前端和后端同步。
基本文件
socket = new WebSocket("ws://" + window.location.host + "/notification/");
socket.onmessage = function(e) {
notificationElement.innerHtml = e.data
}
模型.py
@receiver(post_save, sender=Notification)
def notification_handler(sender, instance, **kwargs):
Group("notification").send({
"text": "This is the new notification",
})
关于Django异步发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47392454/