Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating a Django Project
- Creating a Django App
- Setting Up a Database
- Creating the Chat Models
- Configuring Django Channels
- Creating the Chat Consumer
- Creating the Chat HTML Templates
- Creating the Chat Views
- Testing the Chat Application
- 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.
- Open your terminal or command prompt.
- Create a new directory for your project:
mkdir chat-app
- Navigate to the project directory:
cd chat-app
- Create a virtual environment:
python3 -m venv venv
- Activate the virtual environment:
- On macOS and Linux:
source venv/bin/activate
- On Windows:
venv\Scripts\activate.bat
- On macOS and Linux:
Creating a Django Project
To start building our chat application, we first need to create a new Django project.
- In the project directory, run the command:
django-admin startproject chat_project .
(don’t forget the trailing dot) - 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.
- In the project directory, run the command:
python manage.py startapp chat
- 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.
- Open the
settings.py
file located in thechat_project/chat_project
directory. - 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'), } }
- 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.
- Open the
models.py
file located in thechat
app directory. - 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
- 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
- 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.
- Open the
settings.py
file located in thechat_project/chat_project
directory. - Locate the
INSTALLED_APPS
section and add'channels'
to the list of installed apps. - 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.
- Create a new file named
consumers.py
in thechat
app directory. - 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
.
- Create a new directory named
templates
in thechat
app directory. - Inside the
templates
directory, create another directory namedchat
. - Inside the
chat
directory, create two HTML files:room.html
andindex.html
. - 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>
- 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.
- Open the
views.py
file located in thechat
app directory. - 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'
- Open the
urls.py
file located in thechat
app directory. - 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.
- In your terminal, make sure you are in the project directory and run the following command:
python manage.py runserver
- Open your web browser and navigate to
http://localhost:8000
. - You should see a list of chat rooms. Click on a room to enter.
- In a new browser tab or window, open the same chat room.
- 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.