2 回答

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)記為已讀。

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)
添加回答
舉報(bào)