Create Notification using WebSocket

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]

Welcome @GingerBuns !

What and how are these notifications being sent to Channels? (I don’t see any code here sending data either through the channel layer directly or to the consumer.)

Hi @KenWhitesell thank you for replying.

I thought it sending notification from async def receive.
By retrieving data from db first, sending it to room group then sending it to websocket.
In js I pass it on notifsc.onmessage.

I’m suspect there is something wrong in my consumer.py def get_notif. This is where I try to retrieve data from db. But don’t know how to test it. Tried to use print function in consumer.py but found nothing.

Yes, but what is causing your receive method to execute? (Nothing that I can see.)

Nothing wrong that I can see.

What shoud I add to execute received method?
Also I use this site as reverence to make it.

The receive method of a consumer is executed when the JavaScript in the connected browser sends a dataframe through the websocket to that consumer.

Oh now I get what you mean, I update my JS to send data. But now I get another error.
TypeError: Object of type QuerySet is not JSON serializable
This is because my db return is query?

That is basically it, you can solve this by wrapping the query in a list function:
return list(Notification.objects... )

Thank you very much for your help. It’s working now. :grinning: