Django异步发送通知

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

当管理员向用户添加通知时,我有一个用户通知我想在用户的主页上显示,如 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/

相关文章:

Django 从另一个模型保存方法创建模型实例

django - 如何访问模板中的模型字段详细名称?

python - Django Form提交导致404错误

Django 将自定义表单错误添加到 form.errors

django - 导入错误: import dj_database_url ImportError: No module named 'dj_database_url'

sql - 如何在 Django ORM 查询中包含来自外键对象的数据?

python - Django 中的类别、子类别和产品

django - 关于Django中批量保存对象的问题

python - 想要在django管理页面实现多个表的搜索功能

python - 扩展后无法在 Django 模型上保存图像