New chat message notification Django Channels
One easy way to implement a notification system can be:
When you want to show a new message, manipulate HTML using JS as soon as you get a message on the websocket. And whenever the element has been interacted with, which means the user has read the notification, send a message back to server using the websocket.
Your Notification
can have ForeignKeys
to user and the message along with a BooleanField
for read status. Whenever you are sending the message to the user, you should append the notification_id along the message,
#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
}
...
On the client side,
// 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));
});
You can mark individual/all unread notifications as read according to your need.
I did something similar for a training project, you can check that out for ideas. Github link.