The user wants a boilerplate for a Django project that includes Django Channels for WebSocket support.
Key Components Needed:
- Project Structure: A standard Django layout but modified for Channels (routing, consumers).
- Dependencies:
Django, channels, daphne (or uvicorn/gunicorn), redis (for the Channel Layer).
- Configuration:
INSTALLED_APPS needs channels.
ASGI_APPLICATION setting.
CHANNEL_LAYERS setting (Redis is the industry standard).
- Code:
asgi.py: The entry point for ASGI.
routing.py: URL patterns for WebSockets.
consumers.py: The logic handling WebSocket connections/messages.
- Infrastructure (Boilerplate usually implies Docker/Compose): A
docker-compose.yml to spin up Redis easily is very helpful.
Step-by-Step Plan:
- Prerequisites/Setup: Mention Python version, virtualenv.
- Folder Structure: Visualize the tree.
- Installation:
pip install ...
- Settings (
settings.py): Add apps, configure ASGI, configure Channel Layers.
- ASGI Config (
asgi.py): Connect Django routing to the ASGI app.
- Routing (
routing.py): Define WebSocket URL patterns.
- Consumers (
consumers.py): Create a basic Chat or Echo consumer.
- Frontend (Optional but helpful): A simple HTML template with JS to test the connection.
- Running it: Instructions on how to start the server (using Daphne/Uvicorn).
- Docker (Bonus):
docker-compose.yml for Redis.
Drafting the Content:
-
Project Name: myproject
-
App Name: chat (standard example)
-
Settings:
INSTALLED_APPS = [
...
'channels',
'chat',
]
ASGI_APPLICATION = 'myproject.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
-
Consumers: Use AsyncWebsocketConsumer because it's the modern standard.
-
Frontend: Keep it inline script in a template for simplicity.
Refining the Output:
The user asked for a "boilerplate". This usually means copy-pasteable code blocks. I should organize it logically:
- File structure.
requirements.txt.
- Configuration.
- Backend Logic (Consumers/Routing).
- Frontend (Template).
- Running instructions.
I need to make sure to mention daphne. Since Channels 3.0/4.0, daphne is the default run server, but uvicorn is also popular. I'll stick to the standard daphne approach or just python manage.py runserver which now uses Daphne automatically if installed.
Self-Correction during drafting:
Should I use Docker?
Decision: Yes, setting up Redis locally without Docker is annoying for beginners. Including a docker-compose.yml for Redis is best practice for a "boilerplate".
Final Structure:
- Directory Tree: Visual aid.
- Dependencies:
requirements.txt.
- Project Config:
settings.py, asgi.py.
- App Logic:
routing.py, consumers.py.
- View/Template: To test the socket.
- Infrastructure:
docker-compose.yml for Redis.
- Run Instructions.
Let's write it out.
Here is a complete, modern boilerplate for a Django project using Django Channels (version 4.x) and Redis as the message broker.
This setup includes:
- ASGI configuration for WebSockets.
- Redis setup for the Channel Layer.
- A sample Consumer (WebSocket handler).
- Front-end code to test the connection.
1. Project Structure
We will assume your project is named core and your app is named chat.
my_project/
├── core/ # Project configuration
│ ├── __init__.py
│ ├── asgi.py # Entry point for ASGI/Channels
│ ├── settings.py
│ ├── urls.py
│ └── routing.py # WebSocket URL routing
├── chat/ # Your app
│ ├── __init__.py
│ ├── consumers.py # WebSocket logic (like Views)
│ └── ...
├── manage.py
├── requirements.txt
└── docker-compose.yml # For running Redis easily
2. Requirements (requirements.txt)
You need channels for WebSockets and channels_redis for the backend layer.
Django>=4.2
channels>=4.0
channels_redis>=4.2
daphne>=4.0 # Production ASGI server
3. Configuration (core/settings.py)
Add channels and your app to INSTALLED_APPS. Define the ASGI_APPLICATION and the CHANNEL_LAYERS.
# core/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add Channels and your app
'channels',
'chat',
]
# Point Django to the ASGI application
ASGI_APPLICATION = 'core.asgi.application'
# Channel Layer Configuration (using Redis)
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
# Connects to localhost:6379 (default Redis port)
"hosts": [('127.0.0.1', 6379)],
},
},
}
4. ASGI Setup (core/asgi.py)
This is the entry point. We need to wrap the standard Django ASGI handler with the Channels ProtocolTypeRouter.
# core/asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import chat.routing # Import your app's routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = ProtocolTypeRouter({
# Standard HTTP requests
"http": get_asgi_application(),
# WebSocket requests
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
5. App Routing (chat/routing.py)
Create this file inside your chat app. It works exactly like urls.py but for WebSockets.
# chat/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
# Route for a specific chat room
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
6. The Consumer (chat/consumers.py)
This is the class that handles WebSocket events (connect, disconnect, receive). We will use AsyncWebsocketConsumer for better performance.
# 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
)
# Receive message from WebSocket
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', # This calls the method named 'chat_message'
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
7. Infrastructure (docker-compose.yml)
Channels requires a Redis server to work in production (and realistically, for local development). Save this file in the root and run docker-compose up -d.
version: '3.8'
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
8. Frontend Test Template
Create a simple HTML file in your templates folder to test if the socket connects.
<!-- templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
<!-- Ensure you pass room_name from your Django View -->
<script>
const roomName = "{{ room_name }}";
// Construct the WebSocket URL (ws:// or wss://)
const chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.key === 'Enter') { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</body>
</html>
9. How to Run
- Start Redis: Run
docker-compose up -d.
- Migrate: Run
python manage.py migrate.
- Run Server: Run
python manage.py runserver.
- Note: Since Channels 4.0,
runserver runs Daphne automatically in development mode, supporting both HTTP and WebSockets.
Summary of Logic Flow
- Browser sends WebSocket request to
ws://localhost:8000/ws/chat/lobby/.
- ASGI (
core/asgi.py) detects the ws:// protocol.
- Router (
chat/routing.py) matches the URL pattern.
- Consumer (
chat/consumers.py) connect method is called. It adds the user to a Redis Group named chat_lobby.
- Browser sends JSON
{message: "hello"}.
- Consumer
receive method pushes that message to the Redis Group.
- Redis broadcasts the message back to all Consumers in that group.
- Consumer
chat_message method sends the final JSON back to the browser.