Python and Django: Building a Real-time Chat Application

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a Django Project
  5. Creating a Django App
  6. Setting Up a Database
  7. Creating the Chat Models
  8. Configuring Django Channels
  9. Creating the Chat Consumer
  10. Creating the Chat HTML Templates
  11. Creating the Chat Views
  12. Testing the Chat Application
  13. Conclusion

Introduction

In this tutorial, we will learn how to build a real-time chat application using Python and Django. By the end of this tutorial, you will have a functioning chat application that allows users to send and receive messages in real time.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python and web development concepts. Familiarity with Django and its concepts will also be beneficial. You will need the following software installed on your system:

  • Python 3
  • Django
  • Django Channels

Setup

Before we begin building the chat application, let’s set up our development environment.

  1. Open your terminal or command prompt.
  2. Create a new directory for your project: mkdir chat-app
  3. Navigate to the project directory: cd chat-app
  4. Create a virtual environment: python3 -m venv venv
  5. Activate the virtual environment:
    • On macOS and Linux: source venv/bin/activate
    • On Windows: venv\Scripts\activate.bat

Creating a Django Project

To start building our chat application, we first need to create a new Django project.

  1. In the project directory, run the command: django-admin startproject chat_project . (don’t forget the trailing dot)
  2. This will create a new Django project with the name “chat_project” in the current directory.

Creating a Django App

Now that we have our Django project set up, let’s create a new Django app to contain our chat functionality.

  1. In the project directory, run the command: python manage.py startapp chat
  2. This will create a new Django app with the name “chat” in the current directory.

Setting Up a Database

We need to configure a database for our chat application to store messages and other data. By default, Django uses SQLite, but you can also use other databases like PostgreSQL or MySQL.

  1. Open the settings.py file located in the chat_project/chat_project directory.
  2. Locate the DATABASES section and update the settings accordingly. For example, for SQLite:
     DATABASES = {
         'default': {
             'ENGINE': 'django.db.backends.sqlite3',
             'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
         }
     }
    
  3. Save the file.

Creating the Chat Models

The chat application will have two main models: Room and Message. The Room model will represent a chat room, while the Message model will represent a chat message.

  1. Open the models.py file located in the chat app directory.
  2. Define the Room model:
     from django.db import models
    	
     class Room(models.Model):
         name = models.CharField(max_length=100)
    	
         def __str__(self):
             return self.name
    
  3. Define the Message model:
     from django.db import models
     from django.contrib.auth import get_user_model
    	
     User = get_user_model()
    	
     class Message(models.Model):
         user = models.ForeignKey(User, on_delete=models.CASCADE)
         room = models.ForeignKey(Room, on_delete=models.CASCADE)
         content = models.TextField()
         timestamp = models.DateTimeField(auto_now_add=True)
    	
         def __str__(self):
             return self.content
    
  4. Create the necessary database migrations by running the following command: python manage.py makemigrations

Configuring Django Channels

Django Channels allows us to build real-time applications using Django. Let’s configure it in our project.

  1. Open the settings.py file located in the chat_project/chat_project directory.
  2. Locate the INSTALLED_APPS section and add 'channels' to the list of installed apps.
  3. Below the INSTALLED_APPS section, add the following code:
     ASGI_APPLICATION = 'chat_project.routing.application'
    	
     CHANNEL_LAYERS = {
         'default': {
             'BACKEND': 'channels.layers.InMemoryChannelLayer',
         }
     }
    

    Creating the Chat Consumer

A consumer is a class that handles WebSocket connections in Django Channels. Let’s create a chat consumer to handle incoming WebSocket connections.

  1. Create a new file named consumers.py in the chat app directory.
  2. Open the consumers.py file and add the following code:
     import json
     from channels.generic.websocket import AsyncWebsocketConsumer
    	
     class ChatConsumer(AsyncWebsocketConsumer):
         async def connect(self):
             self.room_name = self.scope['url_route']['kwargs']['room_name']
             self.room_group_name = 'chat_%s' % 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
             )
    	
         # Receive message from WebSocket
         async def receive(self, text_data):
             text_data_json = json.loads(text_data)
             message = text_data_json['message']
    	
             # Send message to room group
             await self.channel_layer.group_send(
                 self.room_group_name,
                 {
                     'type': 'chat_message',
                     'message': message
                 }
             )
    	
         # Receive message from room group
         async def chat_message(self, event):
             message = event['message']
    	
             # Send message to WebSocket
             await self.send(text_data=json.dumps({
                 'message': message
             }))
    

    Creating the Chat HTML Templates

To display the chat interface, we need to create HTML templates. Let’s create two templates: room.html and index.html.

  1. Create a new directory named templates in the chat app directory.
  2. Inside the templates directory, create another directory named chat.
  3. Inside the chat directory, create two HTML files: room.html and index.html.
  4. Open the room.html file and add the following code:
    	
     <!DOCTYPE html>
     <html>
     <head>
         <title>Chat Room</title>
         <script src="{% static 'js/jquery.min.js' %}"></script>
         <script src="{% static 'js/chat.js' %}"></script>
     </head>
     <body>
         <h1>Chat Room: {{ room_name }}</h1>
         <div id="chat-log"></div>
         <input id="chat-message-input" type="text">
         <button id="chat-message-submit">Send</button>
     </body>
     </html>
    	
    
  5. Open the index.html file and add the following code:
    	
     <!DOCTYPE html>
     <html>
     <head>
         <title>Chat Index</title>
     </head>
     <body>
         <h1>Chat Index Page</h1>
         <ul>
             {% for room in room_list %}
                 <li><a href="{% url 'room' room.name %}">{{ room.name }}</a></li>
             {% endfor %}
         </ul>
     </body>
     </html>
    	
    

    Creating the Chat Views

Now, let’s create the views that will handle requests to the chat application.

  1. Open the views.py file located in the chat app directory.
  2. Replace the existing code with the following:
     from django.shortcuts import render
     from django.views.generic import TemplateView
     from .models import Room
    	
     class IndexView(TemplateView):
         template_name = 'chat/index.html'
    	
         def get_context_data(self, **kwargs):
             context = super().get_context_data(**kwargs)
             context['room_list'] = Room.objects.all()
             return context
    	
     class RoomView(TemplateView):
         template_name = 'chat/room.html'
    
  3. Open the urls.py file located in the chat app directory.
  4. Replace the existing code with the following:
     from django.urls import path
     from .views import IndexView, RoomView
    	
     urlpatterns = [
         path('', IndexView.as_view(), name='index'),
         path('<str:room_name>/', RoomView.as_view(), name='room')
     ]
    

    Testing the Chat Application

Finally, let’s test our chat application.

  1. In your terminal, make sure you are in the project directory and run the following command: python manage.py runserver
  2. Open your web browser and navigate to http://localhost:8000.
  3. You should see a list of chat rooms. Click on a room to enter.
  4. In a new browser tab or window, open the same chat room.
  5. Start sending messages in one tab, and you should see them appear in real time in the other tab.

Congratulations! You have successfully built a real-time chat application using Python and Django.

Conclusion

In this tutorial, we learned how to build a real-time chat application using Python and Django. We covered the necessary setup, creating Django models, configuring Django Channels, creating a consumer, and creating HTML templates and views. We also tested the chat application to see it in action.