Django – Simple channels Example

Django is a great python web framework for server side. If we want to communicate with the client it can be done using the request-response model and also using a web socket especially when we want to send push notifications to the client.

This is a very simple example of how to create and communicate using a channel (web socket) it can be used as a starter for any web application with channels need

First step is to create and activate virtual environment

Install django and create a new app

install channels for web sockets support and asgi_redis for using redis-server as a backend

Add the channels and example to the installed apps (in settings.py)

Add the channel configuration at the end of the settings.py file:

It defines the backend as redis server and set the port

install redis server

start the redis server

run migrate and the server

Edit the file urls.py:

Add urls.py file to the folder example

Add a simple view to views.py file:

Add a template folder (below example) and add index.html file:

In the above code we open a web socket on load and connect to the server. We also added 2 buttons to send ‘start’ and ‘stop’ command to the socket and label for data received

Add the file routing.py to chantest directory: (as we declared it in settings.py file)

Add consumer.py file to example directory:

Test your work – click on start to see the generated numbers in the label and click on stop to disable it

You can download the code from github

 

 

Tagged ,

4 thoughts on “Django – Simple channels Example

  1. Thanks Liran B.H

  2. Getting the following error when I do runserver
    CommandError: You have not set ASGI_APPLICATION, which is needed to run the server.

    1. Did you find a solution?

Leave a Reply

Your email address will not be published. Required fields are marked *