Skip to content

WebSocket with Django Channels — Complete Guide

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Websocket with Django Channels. We cover key concepts, practical examples, and best practices to help you master this topic.

Django Channels extends Django to handle WebSocket and other asynchronous protocols. It introduces consumers (similar to views), channel layers for cross-Process communication, and ASGI for async server support.

What You'll Learn

  • ASGI configuration for Django
  • WebSocket consumers and routing
  • Channel layers with Redis
  • Groups for broadcasting
  • WebSocket authentication

Why It Matters

Django is primarily synchronous and HTTP-based. Channels adds async WebSocket support while leveraging Django's ORM, authentication, and session systems.

Real-World Use

Mozilla uses Django Channels for push notifications. Real-time Django applications use Channels for chat, live updates, and WebSocket APIs. The Django community standard for WebSocket is Channels.

flowchart LR
    Client[WebSocket Client] --> ASGI[ASGI Server Daphne/Uvicorn]
    ASGI --> Router[Channel Router]
    Router --> Consumer[WebSocket Consumer]
    Consumer --> ChannelLayer[Channel Layer Redis]
    ChannelLayer --> Group[Group Broadcast]
    Group --> Consumer2[Other Consumers]

Teacher Mindset

Consumers are like views for WebSocket. They handle connect, disconnect, and receive events. Use groups to broadcast messages to multiple consumers. Use channel layers for cross-process communication.

Code Examples

# Example 1: WebSocket consumer
# chat/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}'

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

    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
        }))
# Example 2: Routing configuration
# chat/routing.py
from django.urls import re_path
from . import consumers

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

# asgi.py
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
import chat.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})
# Example 3: Channel layer configuration
# settings.py
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

# Authenticated consumer
from channels.db import database_sync_to_async

class AuthenticatedConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        user = self.scope['user']
        if user.is_anonymous:
            await self.close()
        else:
            await self.accept()

Common Mistakes

  • Forgetting to configure CHANNEL_LAYERS in Django settings
  • Not using AuthMiddlewareStack for authenticated consumers
  • Running Django's development server instead of an ASGI server
  • Blocking the async consumer with synchronous ORM calls
  • Not consuming the Redis channel layer in production

Practice

  1. Set up Django Channels with Redis as the channel layer.
  2. Create a WebSocket consumer for a chat room.
  3. Configure routing and ASGI application.
  4. Add authentication to the WebSocket consumer.
  5. Challenge: Build a notification system that broadcasts to a user-specific group.

FAQ

What is the difference between Django Channels and plain WebSocket?

Channels integrates WebSocket with Django's ORM, auth, sessions, and routing. It provides group broadcasting via channel layers.

Do I need Redis for Django Channels?

Redis is the recommended channel layer backend. You can use an in-memory layer for development.

Can I use Django ORM in async consumers?

Use database_sync_to_async decorator to wrap synchronous ORM calls for use in async consumers.

What ASGI server should I use?

Daphne (official), Uvicorn, or Hypercorn. Do not use Django's runserver for WebSocket.

How do I deploy Django Channels?

Use Daphne as the ASGI server behind Nginx. Configure Nginx for WebSocket proxy pass.

Mini Project

Build a Django Channels chat application with: room-based chat using URL routing, Redis channel layer, authentication via session auth, message persistence to database, and a simple HTML frontend.

What's Next

Next, you will learn about WebSocket integration with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro