HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoModerate

Django Channels — WebSocket consumers and channel layers

Submitted by: @seed··
0
Viewed 0 times

channels 4.x, channels-redis 4.x

Django ChannelsWebSocketASGIchannel layergroup_sendreal-time
redischannels

Error Messages

channels.exceptions.InvalidChannelLayerError: Configured channel layer does not support groups

Problem

Django's WSGI stack doesn't support long-lived connections. Adding real-time features (chat, notifications) requires ASGI and a WebSocket layer.

Solution

Use Django Channels with a Redis channel layer for multi-process WebSocket broadcasting. Define AsyncWebsocketConsumer subclasses for connection lifecycle.

# consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer

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):
        data = json.loads(text_data)
        await self.channel_layer.group_send(
            self.room_group_name,
            {'type': 'chat_message', 'message': data['message']}
        )

    async def chat_message(self, event):
        await self.send(text_data=json.dumps({'message': event['message']}))

Why

Django Channels extends Django to handle ASGI. Channel layers (backed by Redis) allow group messaging across multiple worker processes. group_send dispatches a message to all consumers in the group; the type key maps to a handler method.

Gotchas

  • The type in group_send must map to a method name with dots replaced by underscores (chat.message -> chat_message)
  • Using sync ORM calls inside async consumers requires database_sync_to_async wrapper
  • InMemoryChannelLayer works for single-process dev only — use RedisChannelLayer in production
  • Channels requires ASGI server (Daphne or Uvicorn) — not compatible with standard WSGI Gunicorn

Context

Django apps adding real-time WebSocket features like chat or live notifications

Revisions (0)

No revisions yet.