By KFSys
System Administrator
WebSockets are a protocol that allows real-time, bidirectional communication between a client and a server, making them ideal for applications requiring instant data updates, like chat apps, real-time notifications, and live dashboards. In a Django application, WebSockets can replace traditional HTTP requests, reducing latency and improving the user experience by maintaining an open connection between the server and client.
What This Tutorial Covers:
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Consider switching to WebSockets if:
How WebSockets Differ from HTTP Requests:
Advantages of WebSockets:
Django natively uses HTTP, so to add WebSocket support, we’ll use Django Channels. Django Channels extends Django to handle WebSocket connections and other asynchronous protocols.
pip install channels
settings.py, add channels to the INSTALLED_APPS list:INSTALLED_APPS = [
...,
'channels',
]
pip install channels_redis
settings.py to use Redis:CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6379)],
},
},
}
Consumers in Channels are similar to Django views but are used for handling WebSocket connections.
Create a new app called chat:
python manage.py startapp chat
In chat/consumers.py, create a basic consumer for handling WebSocket connections:
# chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = "chat_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):
data = json.loads(text_data)
message = data['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
}))
Define a routing configuration to direct WebSocket connections to this consumer. In chat/routing.py, add:
# chat/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()),
]
Add this routing to your main project’s asgi.py:
# myproject/asgi.py
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import chat.routing
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
Start Redis (if using Redis for the Channels layer).
Run the Django Server:
python manage.py runserver
const chatSocket = new WebSocket('ws://localhost:8000/ws/chat/');
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
console.log(data.message);
};
chatSocket.onopen = function() {
chatSocket.send(JSON.stringify({ 'message': 'Hello WebSocket!' }));
};
WebSockets are incredibly useful for real-time, interactive applications. With Django Channels, setting up WebSocket support is straightforward, allowing you to create apps with instant feedback and seamless communication.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.