'Django Channels receive message from room group doesn't appear to be working

I am trying to build a notifications system using Django Channels. I completed the intial setup and when I run my server I get confirmation of Handshake and connection confirmed. However, when I view my console log, I cannot see the message to be sent. I also put a print statement on the send_notification function but it is never reached. I am new to using Django Channels so any help would be appreciated. What am I terribly doing wrong?

Here is my ASGI file setup:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clicksource.settings')
from channels.auth import AuthMiddleware, AuthMiddlewareStack
from notifications.routing import websocket_urlpatterns
application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    )
})

Here is my consumers.py:

import json
from channels.generic.websocket import AsyncWebsocketConsumer

class NotificationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'notification_%s' % self.room_name

        # 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
        )

    # Receive message from room group
    async def send_notification(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message':message
        }))

Here is my routing.py:

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/notification/(?P<room_name>\w+)/$', consumers.NotificationConsumer.as_asgi()),
]

And the script in my base.html file:

    <script>
    const roomName = JSON.parse(document.getElementById('room-name').textContent);

    const notificationSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/notification/'
        + roomName
        + '/'
    );

    notificationSocket.onmessage = function(e) {
        const data = JSON.parse(e.data);
        //document.querySelector('#chat-log').value += (data.message + '\n');
        console.log(data);
        document.getElementById("notifications-dropdown").innerHTML = "<li class='dropdown-item'>" + data + "</li><hr class='dropdown-divider'>" + document.getElementById("notifications-dropdown").innerHTML;
        document.getElementById("notification-badge").innerHTML = parseInt(document.getElementById("notification-badge").innerHTML) + 1;
    };

    notificationSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };
</script>


Solution 1:[1]

You need to define .receive() method on NotificationConsumer. Whenever a client sends a message, .receive() gets it and echoes it back to the group and then everyone subscribed to that group gets it.

Check out this link: https://channels.readthedocs.io/en/stable/tutorial/part_3.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smile23