Realtime chat app using Django Channels – Python

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

Django channel:
Channels is a project that takes Django and extends its abilities beyond HTTP – to handle WebSockets, chat protocols, IoT protocols, and more.

Pre-requesting :

Python and Pip
Basic Knowledge of creating Django projects.
Create a Chat App:

In Terminal, create a new Django project named chat app


This HTML code is to create a form with one input field to name the room and submit button. Once the submit button is pressed, the new room is created and redirected to that page.

Write your first consumer

When Django accepts an HTTP request, it consults the root URLconf to lookup a view function and then calls the view function to handle the request. Similarly, when Channels accepts a WebSocket connection, it consults the root routing configuration to lookup a consumer and then calls various functions on the consumer to handle events from the connection.

We will write a basic consumer that accepts WebSocket connections on the path /ws/chat/ROOM_NAME/ that takes any message it receives on the WebSocket and echos it back to the same WebSocket.

Create a new file chat/ and include the following code:

We call the as_asgi() the class method in order to get an ASGI application that will instantiate an instance of our consumer for each user connection. This is similar to Django’s as_view(), which plays the same role for per-request Django view instances.

(Note we use re_path() due to limitations in URLRouter.)

The next step is to point the root routing configuration at the chat.routing module. In mysite/, import AuthMiddlewareStack, URLRouter, and chat.routing; and insert a ‘websocket’ key in the ProtocolTypeRouter list in the following format:

Share this post