DEV Community

Cover image for Django WebSocket tutorial for begineers
Tej Magar
Tej Magar

Posted on • Originally published at

Django WebSocket tutorial for begineers

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😉

Image description

Install the following requirements

pip install django

pip install channels

After installing all the requirements, update the file of your project. Add channels in the list of Installed Apps. See below:

# Application definition

Enter fullscreen mode Exit fullscreen mode

Now, we need to add ASGI_APPLICATION in the 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 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):

        while True:
            data = {
                'number': random.randint(1, 1000)



    def disconnect(self, code):
        print("Socket disconnected with code", code)
Enter fullscreen mode Exit fullscreen mode

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 with the following patterns.

from django.urls import path

from channelsdemo.consumers import NumberGenerator

ws_urlpatterns = [
    path('ws/', NumberGenerator.as_asgi(), name='number-generator')
Enter fullscreen mode Exit fullscreen mode

Modifying file
This file is automatically created when channels was installed. We will use the 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)
Enter fullscreen mode Exit fullscreen mode

Now let's create index.html inside the template directory. Before that, we need to add a template directory to

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
Enter fullscreen mode Exit fullscreen mode

We will monitor the data coming from the WebSocket and display it in the browser.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Websocket example</title>


    body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        background-color: #333;

    #number {
        font-size: 1.6rem;
        color: white;

<p id="number"></p>
    const socket = new WebSocket("ws://localhost:8000/ws/");

    socket.onmessage = function (event) {
        const data = JSON.parse(;
        document.querySelector('#number').innerHTML = data.number;
Enter fullscreen mode Exit fullscreen mode

Our site is almost completed. We just need to add some views to the Django project. Create a file and add the following code.

from django.shortcuts import render

def home(request):
    return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)