【问题标题】:Django async send notificationsDjango 异步发送通知
【发布时间】:2018-05-03 16:45:23
【问题描述】:

当管理员向用户添加通知时,我有一个用户通知,我想在用户的主页上显示我想要在用户主页上显示的 facebook 喜欢或活动提要,django 可以吗?

models.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 这样的系统那样做这个异步。

【问题讨论】:

标签: django django-models django-forms django-templates django-views


【解决方案1】:

@987654321@ 是此用例的最佳解决方案。它是 websocket 并且真正异步,并且可以与您的前端和后端同步实时连接。

base.html

socket = new WebSocket("ws://" + window.location.host + "/notification/");
socket.onmessage = function(e) {
    notificationElement.innerHtml = e.data
}

models.py

@receiver(post_save, sender=Notification)
def notification_handler(sender, instance, **kwargs):
    Group("notification").send({
        "text": "This is the new notification",
    })

【讨论】:

  • @RajaSimon 我迟到了,但你能扩展一下这个答案吗?我正在尝试实现它,但不确定我缺少的部分。我正在使用频道,以便用户可以在一个线程中私下聊天。为了使它起作用,视图需要是什么样的?
  • @Trilla 我不确定您当前的代码库。但总是想group 模式。
  • i.e) 您和您的朋友正在聊天中聊天,并将其视为group
  • 在高层次上,就像你和你的朋友建立某种连接时服务器必须创建组(可能你需要为组ID和消息实现数据库)。如果我了解您的业务逻辑,我可以解释更多。 :)
猜你喜欢
  • 2018-07-05
  • 2021-03-08
  • 2015-05-26
  • 2015-06-28
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多