CodexBloom - Programming Q&A Platform

Django Channels WebSocket consumer not receiving messages when using group_send

👀 Views: 94 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
Django WebSocket Channels Python

I'm relatively new to this, so bear with me. I'm stuck on something that should probably be simple. I'm trying to implement a WebSocket chat feature using Django Channels, but I'm having trouble with my consumer not receiving messages sent to a group. I followed the Django Channels documentation and set up my consumers as follows: ```python # consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) ``` I then set up my routing as follows: ```python # routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer.as_asgi()), ] ``` And my settings for Channels and Redis are configured correctly in `settings.py`: ```python # settings.py ASGI_APPLICATION = 'myproject.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("127.0.0.1", 6379)], }, } } ``` However, when I send a message from the client, the consumer does not seem to receive it, and there are no errors in the console. I can confirm that the WebSocket connection is established successfully, but the messages do not appear in the chat. I tried to log the incoming messages in the `chat_message` method, but it never gets called. I've verified that `django-channels` and `channels-redis` are installed and the versions are compatible. Here are the versions I'm using: - Django: 3.2 - channels: 3.0.3 - channels-redis: 3.3.0 What could be causing my consumer not to receive messages sent to the group? Any help or insight would be appreciated! My team is using Python for this web app. Am I approaching this the right way?