🎸 Django Intermediate

What is Django channels and WebSockets?

Why Interviewers Ask This

Mid-level Django roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Django Channels extends Django to handle asynchronous protocols — primarily WebSockets, but also HTTP long-polling, MQTT, and more. It layers an async event loop on top of Django's synchronous core. Setup: pip install channels channels-redis daphne. Replace WSGI with ASGI: ASGI_APPLICATION = "myproject.asgi.application" CHANNEL_LAYERS = {"default": {"BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": {"hosts": [("127.0.0.1", 6379)]}}}. Consumer (WebSocket handler): 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): 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"]})). URL routing for WebSockets: from channels.routing import ProtocolTypeRouter, URLRouter websocket_urlpatterns = [path("ws/chat/<str:room_name>/", ChatConsumer.as_asgi())]. Run with Daphne: daphne myproject.asgi:application.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.