Build a Real‑Time Django Chatroom with Channels and Vue – Step‑by‑Step Guide
This tutorial walks you through creating a real‑time online chatroom using Django 3, Channels, Redis (or Memurai on Windows), and a Vue front‑end, covering environment setup, dependency installation, project configuration, WebSocket consumer implementation, and front‑end integration.
Creating a Virtual Environment
Use python -m venv django3_env to avoid conflicts with existing Python packages, then activate the environment.
Installing Dependencies
Install Django 3 with pip install django, then Channels with pip install channels and its Redis backend with pip install channels_redis. Because Redis lacks official Windows support, the tutorial uses Memurai as a substitute.
Creating the Django Project
Run django-admin startproject chat_backend and python manage.py startapp chat. Add 'channels' and 'chat' to INSTALLED_APPS. Create a templates folder and configure TEMPLATES and ASGI_APPLICATION in settings.py. Set CHANNEL_LAYERS to use Redis.
Views and URLs
Define index and room view functions in chat/views.py. Create chat/urls.py with paths for the two views and include it in the project’s urls.py.
WebSocket Consumer
Create chat/consumers.py with an AsyncWebsocketConsumer subclass that handles connection, disconnection, receiving messages, and broadcasting them to the group.
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=None, bytes_data=None):
data = json.loads(text_data)
message = data['message']
username = data['username']
await self.channel_layer.group_send(
self.room_group_name,
{'type': 'chat_message', 'message': message, 'username': username}
)
async def chat_message(self, event):
await self.send(text_data=json.dumps({'message': event['message'], 'username': event['username']}))ASGI Routing
Modify chat_backend/asgi.py to route HTTP to Django and WebSocket to the consumer via ProtocolTypeRouter and URLRouter.
import os
from django.core.asgi import get_asgi_application
from django.urls import path
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from chat.consumers import ChatConsumer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chat_backend.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter([
path('ws/<str:room_name>/', ChatConsumer.as_asgi()),
])
),
})Frontend WebSocket Connection
In the Vue front‑end, instantiate a WebSocket object pointing to ws://<host>/ws/<room_name>/ and implement onmessage and onclose callbacks to display incoming chat messages.
// Establish a WebSocket connection
const chatSocket = new WebSocket('ws://' + window.location.host + '/ws/' + roomName + '/');
chatSocket.onclose = function(e) {
console.error('The socket closed unexpectedly');
};
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
if (data.message) {
if (data.username == userName) {
document.querySelector('#chat-record').innerHTML += `<div class="right_msg">${data.username}<div class="right-record"><span>${data.message}</span></div></div><br>`;
} else {
document.querySelector('#chat-record').innerHTML += `<div class="left_msg">${data.username}<div class="left-record"><span>${data.message}</span></div></div><br>`;
}
} else {
alert('消息为空!');
}
};Running the Project
After starting the server, users can open the home page, enter a room name and username, and chat in real time. The current version does not persist chat history and lacks authentication, which are noted as future improvements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
