[Django]-Sending notification to one user using Channels 2

17👍

Most users new to Django-channels 2.x face this problem. let me explain.

self.channel_layer.group_add("gossip", self.channel_name) takes two arguments: room_name and channel_name

When you connect from your browser via socket to this consumer, you are creating a new socket connection called as channel. So, when you open multiple pages in your browser, multiple channels are created. Each channel has a unique Id/name : channel_name

room is a group of channels. If anyone sends a message to the room, all channels in that room will receive that message.

So, if you need to send a notification/message to a single user, then you must create a room only for that particular user.

Assuming that current user is passed in the consumer’s scope.

self.user = self.scope["user"]
self.user_room_name = "notif_room_for_user_"+str(self.user.id) ##Notification room name
await self.channel_layer.group_add(
       self.user_room_name,
       self.channel_name
    )

Whenever you send/broadcast a message to user_room_name, It will only be received by that user.

Leave a comment