Django-guide
Django channels and web sockets
1 min readNov 1, 2021
We’re using Django channels at server side and react.js at client. We’re going to setup very basic configuration of web sockets for full stack project.

Server-side:
Python (Django-channels)
import jsonfrom channels.generic.websocket import WebsocketConsumerclass ProjectConsumer(WebsocketConsumer): def connect(self): print("connected server") self.accept() def disconnect(self, close_code): print("disconnected server") pass def receive(self, text_data): print("text object from frontend",text_data) text_data_json = json.loads(text_data) message = text_data_json['message'] message = text_data print("message",message) self.send(text_data=json.dumps({ 'message': message }))
Client-side:
JavaScript (React js)
export const WebSocketTest = () => {var ws = new WebSocket("ws://localhost:8000/ws/projects/");ws.onopen = function() {// Web Socket is connected, send data using send()const msg = JSON.stringify({"firstName": "Jane","lastName": "Doe",})ws.send(msg);alert("Message is sent...");};ws.onmessage = function (evt) {const data = JSON.parse(evt.data);console.log("received_msg",data["message"])alert("Message is received...");};ws.onclose = function() {// websocket is closed.alert("Connection is closed...");};}
Thank You.