Learn to use Websockets with Django
Last Updated : 03 Jul, 2024
Django Channels is an extension of the Django framework that allows for handling WebSockets, HTTP2, and other protocols. It integrates with Django’s existing ORM and works seamlessly alongside Django views. In this tutorial, we will create a small Django project that displays "GeeksforGeeks" on the homepage and demonstrates how to set up WebSockets using Django Channels.
Step-by-Step Guide How to use Django channels for websocket?
1. Setting Up the Django Project
First, let's create a new Django project. Open your terminal and run the following commands:
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
# Install Django
pip install django
# Create a new Django project
django-admin startproject myproject
# Navigate to the project directory
cd myproject
# Start a new Django app
python manage.py startapp myapp
2. Installing Django Channels
Next, install Django Channels:
pip install channels
Add Channels to your INSTALLED_APPS in myproject/settings.py:
INSTALLED_APPS = [
...
'channels',
'myapp',
]
3. Configuring ASGI
Django Channels requires an ASGI configuration. Update your myproject/asgi.py to include Channels:
Python import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() application = get_default_application()
And update your myproject/settings.py to specify the ASGI application:
Python ASGI_APPLICATION = "myproject.asgi.application"
4. Creating a WebSocket Consumer
Create a WebSocket consumer in myapp/consumers.py:
Python import json from channels.generic.websocket import WebsocketConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data=json.dumps({ 'message': 'GeeksforGeeks' })) def disconnect(self, close_code): pass def receive(self, text_data): pass
5. Defining the Routing
Create a routing configuration in myapp/routing.py:
Python from django.urls import re_path from .consumers import MyConsumer websocket_urlpatterns = [ re_path(r'ws/somepath/$', MyConsumer.as_asgi()), ]
Update myproject/asgi.py to include the routing:
Python from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from myapp.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http": get_default_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), })
6. Creating the Django View
Now, create a simple view to render the homepage in myapp/views.py:
Python from django.shortcuts import render def home(request): return render(request, 'home.html')
Add a URL pattern in myapp/urls.py:
Python from django.urls import path from .views import home urlpatterns = [ path('', home, name='home'), ]
Include myapp URLs in myproject/urls.py:
Python from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
7. Creating the HTML Template
Create a template file myapp/templates/home.html:
HTML <!DOCTYPE html> <html> <head> <title>GeeksforGeeks</title> </head> <body> <h1>GeeksforGeeks</h1> <script> const socket = new WebSocket('ws://' + window.location.host + '/ws/somepath/'); socket.onmessage = function(event) { const data = JSON.parse(event.data); console.log(data.message); }; </script> </body> </html>
8. Running the Server
Finally, run the Django development server:
python manage.py migrate
python manage.py runserver
Navigate to http://127.0.0.1:8000 in your web browser. You should see "GeeksforGeeks" on the homepage and a WebSocket connection being established in the background.
Inspecting WebSocket Connection
Open Developer Tools:
- Open your web browser (e.g., Google Chrome).
- Navigate to http://127.0.0.1:8000 where your Django application is running.
- Right-click on the page and select Inspect or press Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac) to open the Developer Tools.
Go to the Network Tab:
- In the Developer Tools, click on the Network tab.
- This tab displays all network requests made by the page.
Filter for WebSocket:
- In the Network tab, you will see a list of network requests.
- To filter and see only WebSocket connections, click on the WS button which stands for WebSockets.
Inspect the WebSocket Connection:
- You should see a connection to your WebSocket URL (ws://127.0.0.1:8000/ws/somepath/).
- Click on this connection to inspect its details.
- Inside, you can see frames that show the messages being sent and received through the WebSocket.
Video Demonstration
Conclusion
You have successfully set up a Django project with Django Channels to handle WebSockets. This setup allows for real-time communication between the server and clients, enabling dynamic and interactive web applications. This example covers the basics, and you can extend it by implementing more complex WebSocket interactions as needed.
Similar Reads
How To Use WebSocket With FastAPI In this article, we will see what a WebSocket is, why we need Websocket, and how Websocket can be used to make real-time applications. We will see HTTP requests getting upgraded to web socket and how it will allow the server to send data to the client without the client having to send multiple HTTP
5 min read
How to Use WebSocket and Load Balancers? WebSockets are a technology that allows websites and servers to talk to each other in real time. It's like having a phone line that stays open between your browser and a server, so they can send messages back and forth quickly and efficiently without having to reconnect all the time. Important Topic
7 min read
How to Integrate WebSockets with React Redux Integrating WebSockets with Redux allows for real-time bidirectional communication between the client (e.g. a web browser) and the server. This enables applications to push data from the server to the client instantly, facilitating features such as real-time updates, live notifications, and chat app
6 min read
How to Send WebSocket Requests with Postman ? This article will show how to send WebSocket requests in Postman. Postman is a popular collaborative platform for API development. It offers different tools for designing, debugging, and testing an API, making it more efficient. WebSocket is an advanced technology used for real-time bidirectional co
3 min read
Documenting Websocket APIs with Swagger WebSocket APIs offer a powerful way to create real-time, interactive applications by enabling bidirectional communication between clients and servers. Documenting these APIs is crucial for developers to understand and utilize them effectively. Swagger (now known as OpenAPI) is a widely used framewor
3 min read