CodexBloom - Programming Q&A Platform

Django Channels: Consumer not receiving messages from Redis when using async/await

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-18
django channels redis async Python

I'm maintaining legacy code that I'm trying to figure out I'm currently developing a chat application using Django Channels, and I've run into an scenario where my consumer doesn't seem to receive messages from Redis. I'm using Django 3.2 and Channels 3.0 along with Redis as the channel layer. The question arises when I try to send messages to the consumer; it appears that the messages are not being processed as expected. Here’s a snippet of my consumer: ```python from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = 'test_room' self.room_group_name = f'chat_{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): 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'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) ``` I have also set up the Redis layer in my settings.py: ```python CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [ ("127.0.0.1", 6379), ], }, }, } ``` I've ensured that the Redis server is running and can be connected to. However, when I send a message from the frontend via the WebSocket, the `chat_message` method is never called, meaning it seems like the group_send is not reaching the group. I've tried enabling debug logs and confirmed that messages are being sent to Redis, but they don't seem to arrive at the consumer. I also verified that the channel name is unique per connection. Can anyone guide to understand why the consumer is not receiving messages from Redis? Are there any specific configurations needed for async consumers with Redis in Django Channels? This is part of a larger REST API I'm building. Any suggestions would be helpful. Any ideas what could be causing this?