第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

新的聊天消息通知 Django 頻道

新的聊天消息通知 Django 頻道

明月笑刀無情 2021-12-29 20:53:03
我已經(jīng)Django Channels 2.1.2按照教程在我的 Django 應(yīng)用程序中進(jìn)行了設(shè)置,現(xiàn)在需要為新消息設(shè)置通知系統(tǒng)。我想以最簡單的方式做到這一點(diǎn)。我可以通過瀏覽器推送通知來做到這一點(diǎn),但我不想那樣做。我希望它像 Stack Overflow 一樣,其中有一個(gè)紅色數(shù)字代表新消息的實(shí)例。這里的一個(gè)答案說對于通知,您只需要兩個(gè)模型:User和Notification。在連接時(shí)將范圍設(shè)置為當(dāng)前經(jīng)過身份驗(yàn)證的用戶。post_save在您的Notification模型上設(shè)置 信號以觸發(fā)消費(fèi)者方法向通知對象的用戶發(fā)送消息?!艺谂λ伎歼@會是什么樣子,我已經(jīng)有了一個(gè)User模型但沒有Notification一個(gè)。聊天僅在 2 個(gè)用戶之間進(jìn)行,它不是聊天室,而是更多的聊天線程。2個(gè)html模板是inbox.html和thread.html
查看完整描述

2 回答

?
絕地?zé)o雙

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊

實(shí)現(xiàn)通知系統(tǒng)的一種簡單方法可以是:


當(dāng)你想顯示一條新消息時(shí),一旦你在 websocket 上收到消息,就使用 JS 操作 HTML。每當(dāng)與元素進(jìn)行交互時(shí),這意味著用戶已閱讀通知,使用 websocket 將消息發(fā)送回服務(wù)器。


您Notification可以擁有ForeignKeys用戶和消息以及BooleanField閱讀狀態(tài)。每當(dāng)您向用戶發(fā)送消息時(shí),都應(yīng)該在消息中附加 notification_id,


#consumer.py

async def websocket_receive(self, event):

        # when a message is received from the websocket

        print("receive", event)


        message_type = event.get('type', None)  #check message type, act accordingly

        if message_type == "notification_read":

             # Update the notification read status flag in Notification model.

             notification = Notification.object.get(id=notification_id)

             notification.notification_read = True

             notification.save()  #commit to DB

             print("notification read")


        front_text = event.get('text', None)

        if front_text is not None:

            loaded_dict_data = json.loads(front_text)

            msg =  loaded_dict_data.get('message')

            user = self.scope['user']

            username = 'default'

            if user.is_authenticated:

                username = user.username

            myResponse = {

                'message': msg,

                'username': username,

                'notification': notification_id  # send a unique identifier for the notification

            }

            ...

在客戶端,


// thread.html

socket.onmessage = function(e) {

    var data = JSON.parse(event.data);

    // Find the notification icon/button/whatever and show a red dot, add the notification_id to element as id or data attribute.

}

...


$(#notification-element).on("click", function(){

    data = {"type":"notification_read", "username": username, "notification_id": notification_id};

    socket.send(JSON.stringify(data));

});


您可以根據(jù)需要將單個(gè)/所有未讀通知標(biāo)記為已讀。



查看完整回答
反對 回復(fù) 2021-12-29
?
RISEBY

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊

我無法將其標(biāo)記為重復(fù),因?yàn)樗匈p金。但解決方案是,您需要兩個(gè)以上的模型。根據(jù)這篇文章,你models.py應(yīng)該看起來像這樣:


class MessageThread(models.Model):

    title = models.CharField()

    clients = models.ManyToManyField(User, blank=True)


class Message(models.Model):

    date = models.DateField()

    text = models.CharField()

    thread = models.ForeignKey('messaging.MessageThread', on_delete=models.CASCADE)

    sender = models.ForeignKey(User, on_delete=models.SET_NULL)

你consumers.py應(yīng)該是這樣的:


class ChatConsumer(WebSocketConsumer):

    def connect(self):

        if self.scope['user'].is_authenticated:

            self.accept()

            # add connection to existing groups

            for thread in MessageThread.objects.filter(clients=self.scope['user']).values('id'):

                async_to_sync(self.channel_layer.group_add)(thread.id, self.channel_name)

            # store client channel name in the user session

            self.scope['session']['channel_name'] = self.channel_name

            self.scope['session'].save()


    def disconnect(self, close_code):

        # remove channel name from session

        if self.scope['user'].is_authenticated:

            if 'channel_name' in self.scope['session']:

                del self.scope['session']['channel_name']

                self.scope['session'].save()

            async_to_sync(self.channel_layer.group_discard)(self.scope['user'].id, self.channel_name)


查看完整回答
反對 回復(fù) 2021-12-29
  • 2 回答
  • 0 關(guān)注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號