Django WebSocket tutorial for begineers
Tej Magar
Posted on July 2, 2022
In this tutorial, we will make a simple real-time random number generator site using Django WebSocket as shown below. To make things simpler we are not going to use Redis server or channel layers. I will paste the link of the example code at the end of the article. So, let's set up our project😉
Install the following requirements
Django
pip install django
Channels
pip install channels
After installing all the requirements, update the settings.py
file of your project. Add channels in the list of Installed Apps. See below:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels'
]
Now, we need to add ASGI_APPLICATION in the settings.py. We will add it below of the WSGI_APPLICATION.
WSGI_APPLICATION = 'channelsdemo.wsgi.application'
ASGI_APPLICATION = 'channelsdemo.asgi.application'
Now let's create a file named consumers.py and create a class named NumberGenerator which extends WebSocketConsumer class. We will make a loop that generates a random number using random.randint(1, 1000) and json.dumps() converts the dictionary to a text. The text will be sent to the client using self.send()
import json
import random
from time import sleep
from channels.generic.websocket import WebsocketConsumer
class NumberGenerator(WebsocketConsumer):
def connect(self):
self.accept()
while True:
data = {
'number': random.randint(1, 1000)
}
self.send(json.dumps(data))
sleep(1)
def disconnect(self, code):
print("Socket disconnected with code", code)
URL Patterns for the asgi app
We will create new URL patterns for the web sockets. It is same as Django urlpatterns. So, create a file named ws_urlpatterns.py
with the following patterns.
from django.urls import path
from channelsdemo.consumers import NumberGenerator
ws_urlpatterns = [
path('ws/', NumberGenerator.as_asgi(), name='number-generator')
]
Modifying asgi.py file
This file is automatically created when channels was installed. We will use the ws_urlpatterns.py which was created earlier.
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channelsdemo.ws_urlpatterns import ws_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channelsdemo.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': URLRouter(ws_urlpatterns)
})
Now let's create index.html inside the template directory. Before that, we need to add a template directory to settings.py.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Index.html
We will monitor the data coming from the WebSocket and display it in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket example</title>
</head>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #333;
}
#number {
font-size: 1.6rem;
color: white;
}
</style>
<body>
<p id="number"></p>
<script>
const socket = new WebSocket("ws://localhost:8000/ws/");
socket.onmessage = function (event) {
const data = JSON.parse(event.data);
console.log(data);
document.querySelector('#number').innerHTML = data.number;
}
</script>
</body>
</html>
Our site is almost completed. We just need to add some views to the Django project. Create a views.py
file and add the following code.
from django.shortcuts import render
def home(request):
return render(request, 'index.html')
Now we can see the random number every second changing in the browser. If you like this content, check out more articles here.
Github Url: https://github.com/tejmagar/django-channels-websocket-example
Posted on July 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.