Django Channels facilitates support of WebSockets in Django in a manner similar to traditional HTTP views. It wraps Django’s native asynchronous view support, allowing Django projects to handle not only HTTP, but also protocols that require long-running connections, such as WebSockets, MQTT, chatbots, etc.
In this tutorial, we’ll show you how to create a real-time app with Django Channels. To demonstrate with a live example, we’ll create a two-player tic-tac-toe game, as illustrated below. You can access the full source code in my GitHub repository.
Configuring a Django project
Follow the steps outlined below to configure your Django project.
First, install Django and channels. You must also install channels_redis so that channels knows how to interface with Redis.
Run the following command:
pip install django==3.1 pip install channels==3.0 pip install channels_redis==3.2
You should use pip3 for Linux/mac instead of pip and python3 in place of python. I used django==3.1 and channels==3.0, channels_redis==3.2.0 for this guide.
Start the Django project:
django-admin startproject tic_tac_toe
Next, create an app with the name game:
python manage.py startapp game
Add channels and game in the INSTALLED_APPS inside your settings.py:
## settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels','game' ]