Realtime chat app using Django

In today's fast-paced digital world, real-time communication has become integral to our lives. From instant messaging to collaborative team chats, the demand for efficient and interactive chat applications continues to grow.

In this article, we will delve into the world of real-time chat apps using Django, a popular Python web framework renowned for its simplicity and scalability. Whether you are a seasoned developer or a beginner looking to enhance your skills, this guide will provide you with a comprehensive understanding of building a real-time chat app using Django.

Step 1: Setting up the Django Project

First, make sure Django is installed on your system. Open a command-line interface and use the following command to establish a new Django project ?

$ django-admin startproject chatapp
$ cd chatapp

This command will create a new directory named chatapp with all of the files required for a Django project.

Step 2: Creating the Chat App

Create a new Django app within your project ?

$ python manage.py startapp chat

Add the app to your INSTALLED_APPS in settings.py ?

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'chat',
]

Step 3: Designing the Data Model

Define the data model for the chat app. Add the following code to the models.py file in the chat app directory ?

from django.db import models
from django.contrib.auth.models import User

class ChatRoom(models.Model):
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Message(models.Model):
    room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
    sender = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return f'{self.sender.username}: {self.content[:50]}'

The code defines two models: ChatRoom represents a named chat room, and Message represents a message with room, sender, content, and timestamp.

Step 4: Installing Django Channels

Install Django Channels to enable WebSocket support for real-time communication ?

$ pip install channels channels-redis

Configure Channels in your settings.py ?

ASGI_APPLICATION = 'chatapp.asgi.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

Step 5: Creating WebSocket Consumers

Create a consumers.py file in the chat app directory ?

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from django.contrib.auth.models import User
from .models import ChatRoom, Message

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
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        username = self.scope['user'].username

        # Save message to database
        await self.save_message(username, self.room_name, message)

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'username': username
            }
        )

    async def chat_message(self, event):
        message = event['message']
        username = event['username']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message,
            'username': username
        }))

    @database_sync_to_async
    def save_message(self, username, room_name, message):
        user = User.objects.get(username=username)
        room, created = ChatRoom.objects.get_or_create(name=room_name)
        Message.objects.create(sender=user, room=room, content=message)

Step 6: Configuring URLs and Routing

Create a routing.py file in the chat app directory ?

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]

Update your project's asgi.py file ?

import os
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
from chat.routing import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatapp.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})

Step 7: Building the Chat Interface

Create the views in chat/views.py ?

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def chat_room(request, room_name):
    return render(request, 'chat/room.html', {
        'room_name': room_name
    })

def index(request):
    return render(request, 'chat/index.html')

Create the HTML template templates/chat/room.html ?

<!DOCTYPE html>
<html>
<head>
    <title>Chat Room {{ room_name }}</title>
</head>
<body>
    <div id="chat-log"></div>
    <input id="chat-message-input" type="text" placeholder="Type your message...">
    <input id="chat-message-submit" type="button" value="Send">

    <script>
        const roomName = {{ room_name|escapejs }};
        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').innerHTML += 
                '<div><b>' + data.username + ':</b> ' + data.message + '</div>';
        };

        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.keyCode === 13) {
                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>

Step 8: Running Migrations and Testing

Create and apply database migrations ?

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser

Start the development server using Channels ?

$ python manage.py runserver

Key Features Summary

Feature Technology Purpose
Real-time messaging WebSockets Instant message delivery
User authentication Django Auth Secure access control
Message persistence Django ORM Chat history storage
Room management Django Channels Group messaging

Conclusion

Building a real-time chat application with Django Channels provides a robust foundation for modern communication features. The combination of WebSockets, Django's authentication system, and database persistence creates a scalable chat solution. This implementation can be extended with features like typing indicators, message notifications, and user presence to enhance the user experience further.

---
Updated on: 2026-04-02T17:07:16+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements