{"id":4022,"date":"2023-11-04T23:14:00","date_gmt":"2023-11-04T23:14:00","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-chat-application-with-django-channels-and-websocket\/"},"modified":"2023-11-05T05:48:24","modified_gmt":"2023-11-05T05:48:24","slug":"how-to-build-a-chat-application-with-django-channels-and-websocket","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-chat-application-with-django-channels-and-websocket\/","title":{"rendered":"How to Build a Chat Application with Django Channels and WebSocket"},"content":{"rendered":"
In this tutorial, we will learn how to build a real-time chat application using Django Channels and WebSocket. Django Channels is a powerful extension that allows Django to handle WebSockets, HTTP & HTTP2 protocols.<\/p>\n
By the end of this tutorial, you will have a working chat application where users can send and receive messages in real-time. Let’s get started!<\/p>\n
To follow along with this tutorial, you will need the following:<\/p>\n
If you don’t have Python installed, you can download it from the official Python website: https:\/\/www.python.org\/downloads\/<\/a><\/p>\n To install Django and Django Channels, open a terminal or command prompt and run the following commands:<\/p>\n Let’s start by creating a new Django project. Open a terminal and run the following command:<\/p>\n This will create a new directory named Change into the project directory:<\/p>\n Next, create a new Django app within the project. Run the following command:<\/p>\n This will create a new directory named Now, let’s add the newly created app to the We will start by creating a This model represents a basic chat room with a name and a creation timestamp. We will use this model to store information about individual chat rooms.<\/p>\n Run the following command to create the necessary database tables:<\/p>\n Next, let’s create the view that will display the chat room to users. Open the In this code, we are using Django’s Create a new directory named Open the In this template, we are rendering the list of chat rooms and displaying a form for users to send messages. When the form is submitted, we send the message to the WebSocket server using the Now, let’s create the WebSocket consumer that will handle WebSocket connections and messages. Create a new directory named Open the This To connect Django Channels to the WebSocket protocol, we need to define a routing configuration. Create a new file named Open the In this code, we define a WebSocket URL pattern that matches the URL To enable Django Channels, we need to configure ASGI (Asynchronous Server Gateway Interface) application. Open the This code sets up the ASGI application to handle both HTTP and WebSocket requests. The Finally, we need to update the project URL configuration to include the chat app URLs. Open the Now that we have finished setting up our chat application, let’s run the development server and test it out. In a terminal, run the following command:<\/p>\n Open your web browser and visit http:\/\/localhost:8000\/<\/a>. You should see the chat room with a list of chat rooms and a form to send messages.<\/p>\n Open multiple browser windows or tabs and enter the same chat room. Send a message from one window, and you should see the message appear in real-time on all connected windows.<\/p>\n Congratulations! You have successfully built a chat application with Django Channels and WebSocket. Feel free to explore and extend the application further. You can add authentication, implement private messaging, or enhance the user interface.<\/p>\n In this tutorial, we learned how to build a real-time chat application using Django Channels and WebSocket. We covered the steps to set up the project, create the chat model, implement the chat room view and template, create the WebSocket consumer, configure the routing, and run the development server.<\/p>\n By using Django Channels and WebSocket, we were able to create a chat application that enables real-time communication between multiple users. This is just the beginning. You can expand on this application by adding more features to meet your specific requirements.<\/p>\n I hope this tutorial has been helpful in understanding how to build a chat application with Django Channels and WebSocket. Enjoy coding and building real-time applications with Django!<\/p>\n","protected":false},"excerpt":{"rendered":" In this tutorial, we will learn how to build a real-time chat application using Django Channels and WebSocket. Django Channels is a powerful extension that allows Django to handle WebSockets, HTTP & HTTP2 protocols. By the end of this tutorial, you will have a working chat application where users can Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[875,876,874],"yoast_head":"\npip install django\npip install channels\n<\/code><\/pre>\n
Setting up the Django Project<\/h2>\n
django-admin startproject chatapp\n<\/code><\/pre>\n
chatapp<\/code> with the basic structure of a Django project.<\/p>\n
cd chatapp\n<\/code><\/pre>\n
python manage.py startapp chat\n<\/code><\/pre>\n
chat<\/code> with the basic structure of a Django app.<\/p>\n
INSTALLED_APPS<\/code> list in the
settings.py<\/code> file:<\/p>\n
INSTALLED_APPS = [\n # ...\n 'chat',\n # ...\n]\n<\/code><\/pre>\n
Creating the Chat Model<\/h2>\n
Chat<\/code> model to represent a chat room. Open the
chat\/models.py<\/code> file and add the following code:<\/p>\n
from django.db import models\n\nclass Chat(models.Model):\n name = models.CharField(max_length=255)\n created_at = models.DateTimeField(auto_now_add=True)\n<\/code><\/pre>\n
python manage.py migrate\n<\/code><\/pre>\n
Creating the Chat Room View<\/h2>\n
chat\/views.py<\/code> file and add the following code:<\/p>\n
from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom .models import Chat\n\n\nclass ChatRoomView(TemplateView):\n template_name = 'chat\/chat_room.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['chats'] = Chat.objects.all()\n return context\n<\/code><\/pre>\n
TemplateView<\/code> class to render a template file named
chat_room.html<\/code>. We also fetch all chat rooms from the database and pass them to the template context.<\/p>\n
Creating the Chat Room Template<\/h2>\n
templates<\/code> inside the
chat<\/code> directory. Then, create a new file named
chat_room.html<\/code> inside the
templates<\/code> directory.<\/p>\n
chat\/templates\/chat_room.html<\/code> file and add the following code:<\/p>\n
<!DOCTYPE html>\n<html>\n<head>\n <title>Chat Room<\/title>\n <script type=\"text\/javascript\" src=\"https:\/\/code.jquery.com\/jquery-3.6.0.min.js\"><\/script>\n<\/head>\n<body>\n <h1>Chat Room<\/h1>\n\n <div id=\"chats\">\n {% for chat in chats %}\n <p>{{ chat.name }}<\/p>\n {% endfor %}\n <\/div>\n\n <form id=\"chat-form\" method=\"POST\">\n {% csrf_token %}\n <input type=\"text\" name=\"message\" id=\"message\" placeholder=\"Enter a message\" \/>\n <button type=\"submit\">Send<\/button>\n <\/form>\n\n <script type=\"text\/javascript\">\n $(document).ready(function() {\n \/\/ Establish WebSocket connection\n const socket = new WebSocket('ws:\/\/localhost:8000\/ws\/chat\/');\n\n \/\/ Handle incoming WebSocket messages\n socket.onmessage = function(event) {\n const message = JSON.parse(event.data);\n $('#chats').append('<p>' + message.message + '<\/p>');\n }\n\n \/\/ Handle form submission\n $('#chat-form').on('submit', function(event) {\n event.preventDefault();\n\n const message = $('#message').val();\n socket.send(JSON.stringify({'message': message}));\n\n $('#message').val('');\n });\n });\n <\/script>\n<\/body>\n<\/html>\n<\/code><\/pre>\n
socket.send()<\/code> method.<\/p>\n
Creating the WebSocket Consumer<\/h2>\n
consumers<\/code> inside the
chat<\/code> directory. Then, create a new file named
chat_consumer.py<\/code> inside the
consumers<\/code> directory.<\/p>\n
chat\/consumers\/chat_consumer.py<\/code> file and add the following code:<\/p>\n
from channels.generic.websocket import AsyncWebsocketConsumer\n\n\nclass ChatConsumer(AsyncWebsocketConsumer):\n async def connect(self):\n self.chat_name = self.scope['url_route']['kwargs']['chat_name']\n self.chat_group_name = 'chat_%s' % self.chat_name\n\n # Join chat room group\n await self.channel_layer.group_add(\n self.chat_group_name,\n self.channel_name\n )\n\n await self.accept()\n\n async def disconnect(self, close_code):\n # Leave chat room group\n await self.channel_layer.group_discard(\n self.chat_group_name,\n self.channel_name\n )\n\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n\n # Send message to chat room group\n await self.channel_layer.group_send(\n self.chat_group_name,\n {\n 'type': 'chat_message',\n 'message': message\n }\n )\n\n async def chat_message(self, event):\n message = event['message']\n\n # Send message to WebSocket\n await self.send(text_data=json.dumps({\n 'message': message\n }))\n<\/code><\/pre>\n
ChatConsumer<\/code> class is a WebSocket consumer that handles the WebSocket connection, disconnection, and incoming messages. When a message is received, it sends the message to the chat room group, which broadcasts it to all connected clients.<\/p>\n
Routing WebSocket URLs<\/h2>\n
routing.py<\/code> in the project directory.<\/p>\n
chatapp\/routing.py<\/code> file and add the following code:<\/p>\n
from django.urls import path\nfrom .consumers import ChatConsumer\n\nwebsocket_urlpatterns = [\n path('ws\/chat\/<str_chat_name>\/', ChatConsumer.as_asgi()),\n]\n<\/code><\/pre>\n
ws\/chat\/<chat_name>\/<\/code> and maps it to the
ChatConsumer<\/code> class.<\/p>\n
Configuring ASGI Application<\/h2>\n
chatapp\/asgi.py<\/code> file and update the following code:<\/p>\n
import os\nfrom django.core.asgi import get_asgi_application\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom chatapp.routing import websocket_urlpatterns\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatapp.settings')\n\napplication = ProtocolTypeRouter(\n {\n 'http': get_asgi_application(),\n 'websocket': URLRouter(websocket_urlpatterns)\n }\n)\n<\/code><\/pre>\n
URLRouter<\/code> maps the WebSocket URLs to the appropriate consumers.<\/p>\n
Updating the Project URL Configuration<\/h2>\n
chatapp\/urls.py<\/code> file and add the following code:<\/p>\n
from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin\/', admin.site.urls),\n path('', include('chat.urls')),\n]\n<\/code><\/pre>\n
Running the Development Server<\/h2>\n
python manage.py runserver\n<\/code><\/pre>\n
Conclusion<\/h2>\n