Hi I’m trying to make Notification using Websocket.
This is what I make so far.
consumer.py
class NotifConsumer(AsyncWebsocketConsumer):
async def connect(self):
currusr_id = self.scope['user'].id
self.room_group_name = f'{currusr_id}'
# Join room group
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
async def receive(self, text_data=None, bytes_data=None):
data = json.loads(text_data)
usr_usrnm = data['username']
usr = await self.get_user(usr_usrnm)
# Get data from DB
notifs = await self.get_notif(usr)
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'send_notif',
'notifs': notifs
},
)
# Receive message from room group
async def send_notif(self, event):
notifs = event['notifs']
# Send message to WebSocket
await self.send(
text_data=json.dumps(
{
'notifs': notifs
}
)
)
@database_sync_to_async
def get_notif(self, currusr):
return Notification.objects.filter(receiver=currusr, read=False).values('chat__sender__username').annotate(scount=Count('chat__sender'))
routing.py
path('ws/notif', consumers.NotifConsumer.as_asgi())
index.js
// Notification Consumer
const notifsc = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/notif'
);
notifsc.onopen = function(e){
console.log("Notification consumer online");
notifsc.send(JSON.stringify({
"username": notifusr
}))
};
notifsc.onclose = function(e){
console.log("Notification consumer closed");
};
notifsc.onmessage = function(e) {
const data = JSON.parse(e.data);
console.log(data);
};
So when I’m running it, it seems to be working. When I checked console there are this log.
Notification consumer online
But I failed to get notifs data that I send to websocket.
Update
Console log
Notification consumer online
Notification consumer closed
Terminal
TypeError: Object of type QuerySet is not JSON serializable
WebSocket DISCONNECT /ws/notif [127.0.0.1:59494]