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 ProjectFirst, 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 ChannelsNext, install Django Channels:
pip install channels Add Channels to your INSTALLED_APPS in myproject/settings.py:
INSTALLED_APPS = [ ... 'channels', 'myapp', ] 
3. Configuring ASGIDjango 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 ConsumerCreate 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 RoutingCreate 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 ViewNow, 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 TemplateCreate 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 ServerFinally, 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 ConnectionOpen 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 DemonstrationConclusionYou 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.
|