This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Django Channels Tutorial

Our copy of the Django Channels tutorial, adapted for uv and your locallibrary project.

Channels allows you to use WebSockets and other non-HTTP protocols in your Django site. For example you might want to use WebSockets to allow a page on your site to immediately receive updates from your Django server without using HTTP long-polling or other expensive techniques.

In this tutorial we will build a simple chat server, where you can join an online room, post messages to the room, and have others in the same room see those messages immediately.

  1. Part 1: Basic Setup
  2. Part 2: Implement a Chat Server
  3. Part 3: Rewrite Chat Server as Asynchronous
  4. Part 4: Automated Testing

How this copy differs from the original

This is a copy of the official Channels tutorial, changed to match the way we have worked in our fork of the MDN Django Tutorial:

  • You don’t create a new project. The chat app goes into your existing locallibrary repository, next to catalog. Everywhere the original says mysite, this copy says locallibrary_config.
  • Dependencies are managed with uv. pip install becomes uv add, and every command is run with uv run python ….
  • Edits to existing files are additions. The original shows complete settings.py and urls.py contents because it assumes a new, empty project. Here you only add lines, so you keep what you built for catalog.
  • Part 4’s tests use a separate database file. The original’s test settings would delete your development database; this copy’s don’t.
  • Part 4 doesn’t need a manual chromedriver install. Selenium downloads the right driver itself.

This copy was checked on 2026-09-29 with Channels 4.3.2, Daphne 4.2.3, channels-redis 4.3.0, Selenium 4.49, Django 6.1.1, and Python 3.14.


The original tutorial is Copyright (c) Django Software Foundation and individual contributors, and is used under its BSD 3-Clause license.

1 - Tutorial Part 1: Basic Setup

Add Channels and Daphne to locallibrary and create the chat app’s index page.

In this tutorial we will build a simple chat server. It will have two pages:

  • An index view that lets you type the name of a chat room to join.
  • A room view that lets you see messages posted in a particular chat room.

The room view will use a WebSocket to communicate with the Django server and listen for any messages that are posted.

We assume that you have completed our fork of the MDN Django Tutorial so far, and that you have your locallibrary repository: a uv project with manage.py, pyproject.toml, and uv.lock at its root, the locallibrary_config project package, and the catalog app. Every command in this tutorial is run from that root folder.

You can check which version of Django your project uses by running the following command in your terminal:

uv run python -m django --version

Installing Channels and Daphne

Add Channels, together with the Daphne server, to your project:

uv add "channels[daphne]"

Just like uv add "django" did when you set up your project, this records the dependency in pyproject.toml, installs it into .venv, and pins the exact versions in uv.lock. Commit both files.

You can check that they’re installed by running the following command:

uv run python -c "import channels; import daphne; print(channels.__version__, daphne.__version__)"

This tutorial was checked with Channels 4.3.2 and Daphne 4.2.3, on Django 6.1 and Python 3.14.

Redis

This tutorial also uses Docker to install and run Redis. We use Redis as the backing store for the channel layer, which is an optional component of the Channels library that we use in the tutorial. Install Docker from its official website - there are official runtimes for Mac OS and Windows that make it easy to use, and packages for many Linux distributions where it can run natively.

Creating the Chat app

You don’t need to create a project: you already have one. We will put the code for the chat server in its own app, alongside catalog.

Make sure you’re in the same directory as manage.py and type this command:

uv run python manage.py startapp chat

That’ll create a directory chat next to catalog, which is laid out like this:

chat/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

For the purposes of this tutorial, we will only be working with chat/views.py and chat/__init__.py. So remove all other files from the chat directory.

After removing unnecessary files, the chat directory should look like:

chat/
    __init__.py
    views.py

We need to tell our project that the chat app is installed. Edit the locallibrary_config/settings.py file and add 'chat' to the end of the INSTALLED_APPS setting, after catalog. Don’t remove anything that’s already there. It’ll look like this:

# locallibrary_config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Add our new application
    'catalog.apps.CatalogConfig', # This object was created for us in /catalog/apps.py
    'chat',
]

Add the index view

We will now create the first view, an index view that lets you type the name of a chat room to join.

Create a templates directory in your chat directory. Within the templates directory you have just created, create another directory called chat, and within that create a file called index.html to hold the template for the index view.

Your chat directory should now look like:

chat/
    __init__.py
    templates/
        chat/
            index.html
    views.py

Put the following code in chat/templates/chat/index.html:

<!-- chat/templates/chat/index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Rooms</title>
    <link rel="icon" href="https://fav.mhciael.com/πŸ’¬">
</head>

<body>
    <form>
        What chat room would you like to enter?<br>
        <input id="room-name-input" type="text" size="100"><br>
        <button id="room-name-submit" type="submit">Enter</button>
    </form>
    <script>
        document.querySelector('#room-name-input').focus();
        const form = document.querySelector('form');

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var roomName = document.querySelector('#room-name-input').value;
            window.location.pathname = '/chat/' + roomName + '/';
        });
    </script>
</body>

</html>

Create the view function for the room view. Put the following code in chat/views.py:

# chat/views.py
from django.shortcuts import render


def index(request):
    return render(request, "chat/index.html")

To call the view, we need to map it to a URL - and for this we need a URLconf.

To create a URLconf in the chat directory, create a file called urls.py. Your app directory should now look like:

chat/
    __init__.py
    templates/
        chat/
            index.html
    urls.py
    views.py

In the chat/urls.py file include the following code:

# chat/urls.py
from django.urls import path

from . import views


urlpatterns = [
    path("", views.index, name="index"),
]

The next step is to point the root URLconf at the chat.urls module. Your locallibrary_config/urls.py already imports include() and already includes catalog.urls. Add the chat app in the same style, right after the catalog block:

# locallibrary_config/urls.py
# (after the existing catalog block)
urlpatterns += [
    path('chat/', include('chat.urls')),
]

Leave the admin, catalog, redirect, and static-files entries as they are.

Let’s verify that the index view works. Run the following command:

uv run python manage.py runserver

You’ll see output like the following on the command line:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 29, 2026 - 09:28:06
Django version 6.1.1, using settings 'locallibrary_config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Unlike in the original tutorial, you won’t see a warning about unapplied migrations, because you already ran migrate for catalog.

Go to http://127.0.0.1:8000/chat/ πŸ”— in your browser and you should see the text “What chat room would you like to enter?” along with a text input to provide a room name. (The site root still redirects to catalog/, so type the /chat/ path yourself.)

Type in “lobby” as the room name and press enter. You should be redirected to the room view at http://127.0.0.1:8000/chat/lobby/ but we haven’t written the room view yet, so you’ll get a “Page not found” error page.

Go to the terminal where you ran the runserver command and press Control-C to stop the server.

Integrate the Channels library

So far we’ve just created a regular Django app; we haven’t used the Channels library at all. Now it’s time to integrate Channels.

Let’s start by creating a routing configuration for Channels. A Channels routing configuration is an ASGI application that is similar to a Django URLconf, in that it tells Channels what code to run when an HTTP request is received by the Channels server.

Start by replacing the contents of the locallibrary_config/asgi.py file with the following code:

# locallibrary_config/asgi.py
import os

from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locallibrary_config.settings")

application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        # Just HTTP for now. (We can add other protocols later.)
    }
)

Now add the Daphne library to the list of installed apps, in order to enable an ASGI version of the runserver command.

Edit the locallibrary_config/settings.py file and add 'daphne' to the top of the INSTALLED_APPS setting. It’ll look like this:

# locallibrary_config/settings.py
INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Add our new application
    'catalog.apps.CatalogConfig', # This object was created for us in /catalog/apps.py
    'chat',
]

You’ll also need to point Daphne at the root routing configuration. Edit the locallibrary_config/settings.py file again and add the following to the bottom of it:

# locallibrary_config/settings.py
# Daphne
ASGI_APPLICATION = "locallibrary_config.asgi.application"

With Daphne now in the installed apps, it will take control of the runserver command, replacing the standard Django development server with the ASGI compatible version.

Let’s ensure that the Channels development server is working correctly. Run the following command:

uv run python manage.py runserver

You’ll see output like the following on the command line:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 29, 2026 - 09:28:06
Django version 6.1.1, using settings 'locallibrary_config.settings'
Starting ASGI/Daphne version 4.2.3 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Notice the line beginning with Starting ASGI/Daphne …. This indicates that the Daphne development server has taken over from the Django development server.

Go to http://127.0.0.1:8000/chat/ πŸ”— in your browser and you should still see the index page that we created before. Your catalog pages at http://127.0.0.1:8000/catalog/ πŸ”— still work too: Daphne serves them the same way.

Go to the terminal where you ran the runserver command and press Control-C to stop the server.

This tutorial continues in Tutorial 2.

2 - Tutorial Part 2: Implement a Chat Server

Add the room view, a WebSocket consumer, and a Redis-backed channel layer.

This tutorial begins where Tutorial 1 left off. We’ll get the room page working so that you can chat with yourself and others in the same room.

Add the room view

We will now create the second view, a room view that lets you see messages posted in a particular chat room.

Create a new file chat/templates/chat/room.html. Your app directory should now look like:

chat/
    __init__.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py

Create the view template for the room view in chat/templates/chat/room.html:

<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Room</title>
    <link rel="icon" href="https://fav.mhciael.com/πŸ’¬">
</head>

<body>
    <form>
        <textarea id="chat-log" cols="100" rows="20"></textarea><br>
        <input id="chat-message-input" type="text" size="100"><br>
        <input id="chat-message-submit" type="button" value="Send">
        {{ room_name|json_script:"room-name" }}
    </form>
    <script>
        const roomName = JSON.parse(document.getElementById('room-name').textContent);

        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/chat/'
            + roomName
            + '/'
        );

        chatSocket.onmessage = function (e) {
            const data = JSON.parse(e.data);
            document.querySelector('#chat-log').value += (data.message + '\n');
        };

        chatSocket.onclose = function (e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();


        document.querySelector('form').addEventListener('submit', (e) => {
            e.preventDefault();
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message
            }));
            messageInputDom.value = '';
        });
    </script>
</body>

</html>

Create the view function for the room view in chat/views.py:

# chat/views.py
from django.shortcuts import render


def index(request):
    return render(request, "chat/index.html")


def room(request, room_name):
    return render(request, "chat/room.html", {"room_name": room_name})

Create the route for the room view in chat/urls.py:

# chat/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("<str:room_name>/", views.room, name="room"),
]

Start the Channels development server:

uv run python manage.py runserver

Go to http://127.0.0.1:8000/chat/ πŸ”— in your browser to see the index page.

Type in “lobby” as the room name and press enter. You should be redirected to the room page at http://127.0.0.1:8000/chat/lobby πŸ”— which now displays an empty chat log.

Type the message “hello” and press enter. Nothing happens. In particular the message does not appear in the chat log. Why?

The room view is trying to open a WebSocket to the URL ws://127.0.0.1:8000/ws/chat/lobby/ but we haven’t created a consumer that accepts WebSocket connections yet. If you open your browser’s JavaScript console, you should see an error that looks like:

WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/lobby/' failed: Unexpected response code: 500

Write your first consumer

When Django accepts an HTTP request, it consults the root URLconf to lookup a view function, and then calls the view function to handle the request. Similarly, when Channels accepts a WebSocket connection, it consults the root routing configuration to lookup a consumer, and then calls various functions on the consumer to handle events from the connection.

We will write a basic consumer that accepts WebSocket connections on the path /ws/chat/ROOM_NAME/ that takes any message it receives on the WebSocket and echos it back to the same WebSocket.

Create a new file chat/consumers.py. Your app directory should now look like:

chat/
    __init__.py
    consumers.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py

Put the following code in chat/consumers.py:

# chat/consumers.py
import json

from channels.generic.websocket import WebsocketConsumer


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        self.send(text_data=json.dumps({"message": message}))

This is a synchronous WebSocket consumer that accepts all connections, receives messages from its client, and echos those messages back to the same client. For now it does not broadcast messages to other clients in the same room.

We need to create a routing configuration for the chat app that has a route to the consumer. Create a new file chat/routing.py. Your app directory should now look like:

chat/
    __init__.py
    consumers.py
    routing.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py

Put the following code in chat/routing.py:

# chat/routing.py
from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
]

We call the as_asgi() classmethod in order to get an ASGI application that will instantiate an instance of our consumer for each user-connection. This is similar to Django’s as_view(), which plays the same role for per-request Django view instances.

(Note we use re_path() due to limitations in URLRouter.)

The next step is to point the main ASGI configuration at the chat.routing module. Replace the contents of locallibrary_config/asgi.py with the code below. The highlighted lines are what changed since you edited this file in Part 1:

  • Imports: AuthMiddlewareStack and AllowedHostsOriginValidator are new, and URLRouter joins ProtocolTypeRouter on the existing channels.routing line.
  • django_asgi_app: get_asgi_application() is now called before chat.routing is imported, and its result is saved in django_asgi_app. The comment above it explains why the order matters.
  • from chat.routing import websocket_urlpatterns: this import is new. It deliberately sits below the get_asgi_application() call rather than at the top of the file with the other imports.
  • "http": now uses the saved django_asgi_app instead of calling get_asgi_application() again.
  • "websocket": this key is new and replaces the # Just HTTP for now comment.
# locallibrary_config/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locallibrary_config.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

from chat.routing import websocket_urlpatterns

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

This root routing configuration specifies that when a connection is made to the Channels development server, the ProtocolTypeRouter will first inspect the type of connection. If it is a WebSocket connection (ws:// or wss://), the connection will be given to the AuthMiddlewareStack.

The AuthMiddlewareStack will populate the connection’s scope with a reference to the currently authenticated user, similar to how Django’s AuthenticationMiddleware populates the request object of a view function with the currently authenticated user. (Scopes will be discussed later in this tutorial.) Then the connection will be given to the URLRouter.

The URLRouter will examine the HTTP path of the connection to route it to a particular consumer, based on the provided url patterns.

Let’s verify that the consumer for the /ws/chat/ROOM_NAME/ path works. Django’s session framework needs the database, which you already migrated while building catalog. Run migrate anyway to be sure, and then start the Channels development server:

uv run python manage.py migrate

You should see:

Operations to perform:
  Apply all migrations: admin, auth, catalog, contenttypes, sessions
Running migrations:
  No migrations to apply.

Then start the server:

uv run python manage.py runserver

Go to the room page at http://127.0.0.1:8000/chat/lobby πŸ”— which now displays an empty chat log.

Type the message “hello” and press enter. You should now see “hello” echoed in the chat log.

However if you open a second browser tab to the same room page at http://127.0.0.1:8000/chat/lobby πŸ”— and type in a message, the message will not appear in the first tab. For that to work, we need to have multiple instances of the same ChatConsumer be able to talk to each other. Channels provides a channel layer abstraction that enables this kind of communication between consumers.

Go to the terminal where you ran the runserver command and press Control-C to stop the server.

Enable a channel layer

A channel layer is a kind of communication system. It allows multiple consumer instances to talk with each other, and with other parts of Django.

A channel layer provides the following abstractions:

  • A channel is a mailbox where messages can be sent to. Each channel has a name. Anyone who has the name of a channel can send a message to the channel.

  • A group is a group of related channels. A group has a name. Anyone who has the name of a group can add/remove a channel to the group by name and send a message to all channels in the group. It is not possible to enumerate what channels are in a particular group.

Every consumer instance has an automatically generated unique channel name, and so can be communicated with via a channel layer.

In our chat application we want to have multiple instances of ChatConsumer in the same room communicate with each other. To do that we will have each ChatConsumer add its channel to a group whose name is based on the room name. That will allow ChatConsumers to transmit messages to all other ChatConsumers in the same room.

We will use a channel layer that uses Redis as its backing store. To start a Redis server on port 6379, run the following command in a separate terminal (press Control-C to stop it):

docker run --rm -p 6379:6379 redis:7

We need to install channels_redis so that Channels knows how to interface with Redis. Run the following command:

uv add channels-redis

Commit the updated pyproject.toml and uv.lock again.

Before we can use a channel layer, we must configure it. Edit the locallibrary_config/settings.py file and add a CHANNEL_LAYERS setting to the bottom, below the ASGI_APPLICATION line you added in Part 1. It should look like:

# locallibrary_config/settings.py
# Channels
ASGI_APPLICATION = "locallibrary_config.asgi.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

Let’s make sure that the channel layer can communicate with Redis. Open a Django shell and run the following commands:

uv run python manage.py shell
17 objects imported automatically (use -v 2 for details).

>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync
>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
>>> async_to_sync(channel_layer.receive)('test_channel')
{'type': 'hello'}

(The number of objects the shell imports automatically depends on your models; that’s the same auto-import you’ve seen in the shell before.)

Type Control-D (or exit()) to exit the Django shell.

Now that we have a channel layer, let’s use it in ChatConsumer. Put the following code in chat/consumers.py, replacing the old code:

# chat/consumers.py
import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"chat_{self.room_name}"

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name, self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name, self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat.message", "message": message}
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        self.send(text_data=json.dumps({"message": message}))

When a user posts a message, a JavaScript function will transmit the message over WebSocket to a ChatConsumer. The ChatConsumer will receive that message and forward it to the group corresponding to the room name. Every ChatConsumer in the same group (and thus in the same room) will then receive the message from the group and forward it over WebSocket back to JavaScript, where it will be appended to the chat log.

Several parts of the new ChatConsumer code deserve further explanation:

  • self.scope["url_route"]["kwargs"]["room_name"]

    • Obtains the 'room_name' parameter from the URL route in chat/routing.py that opened the WebSocket connection to the consumer.
    • Every consumer has a scope that contains information about its connection, including in particular any positional or keyword arguments from the URL route and the currently authenticated user if any.
  • self.room_group_name = f"chat_{self.room_name}"

    • Constructs a Channels group name directly from the user-specified room name, without any quoting or escaping.
    • Group names may only contain alphanumerics, hyphens, underscores, or periods. Therefore this example code will fail on room names that have other characters.
  • async_to_sync(self.channel_layer.group_add)(...)

    • Joins a group.
    • The async_to_sync(...) wrapper is required because ChatConsumer is a synchronous WebsocketConsumer but it is calling an asynchronous channel layer method. (All channel layer methods are asynchronous.)
    • Group names are restricted to ASCII alphanumerics, hyphens, and periods only and are limited to a maximum length of 100 in the default backend. Since this code constructs a group name directly from the room name, it will fail if the room name contains any characters that aren’t valid in a group name or exceeds the length limit.
  • self.accept()

    • Accepts the WebSocket connection.
    • If you do not call accept() within the connect() method then the connection will be rejected and closed. You might want to reject a connection for example because the requesting user is not authorized to perform the requested action.
    • It is recommended that accept() be called as the last action in connect() if you choose to accept the connection.
  • async_to_sync(self.channel_layer.group_discard)(...)

    • Leaves a group.
  • async_to_sync(self.channel_layer.group_send)

    • Sends an event to a group.
    • An event has a special 'type' key corresponding to the name of the method that should be invoked on consumers that receive the event. This translation is done by replacing . with _, thus in this example, chat.message calls the chat_message method.

Let’s verify that the new consumer for the /ws/chat/ROOM_NAME/ path works. To start the Channels development server, run the following command:

uv run python manage.py runserver

Open a browser tab to the room page at http://127.0.0.1:8000/chat/lobby/. Open a second browser tab to the same room page.

In the second browser tab, type the message “hello” and press enter. You should now see “hello” echoed in the chat log in both the second browser tab and in the first browser tab.

You now have a basic fully-functional chat server!

This tutorial continues in Tutorial 3.

3 - Tutorial Part 3: Rewrite Chat Server as Asynchronous

Rewrite ChatConsumer as an asynchronous consumer.

This tutorial begins where Tutorial 2 left off. We’ll rewrite the consumer code to be asynchronous rather than synchronous to improve its performance.

Rewrite the consumer to be asynchronous

The ChatConsumer that we have written is currently synchronous. Synchronous consumers are convenient because they can call regular synchronous I/O functions such as those that access Django models without writing special code. However asynchronous consumers can provide a higher level of performance since they don’t need to create additional threads when handling requests.

ChatConsumer only uses async-native libraries (Channels and the channel layer) and in particular it does not access synchronous code. Therefore it can be rewritten to be asynchronous without complications.

Let’s rewrite ChatConsumer to be asynchronous. Put the following code in chat/consumers.py:

# chat/consumers.py
import json

from channels.generic.websocket import AsyncWebsocketConsumer


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"chat_{self.room_name}"

        # Join room group
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name, {"type": "chat.message", "message": message}
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        await self.send(text_data=json.dumps({"message": message}))

This new code for ChatConsumer is very similar to the original code, with the following differences:

  • ChatConsumer now inherits from AsyncWebsocketConsumer rather than WebsocketConsumer.
  • All methods are async def rather than just def.
  • await is used to call asynchronous functions that perform I/O.
  • async_to_sync is no longer needed when calling methods on the channel layer.

Let’s verify that the consumer for the /ws/chat/ROOM_NAME/ path still works. Make sure Redis is still running, then start the Channels development server:

uv run python manage.py runserver

Open a browser tab to the room page at http://127.0.0.1:8000/chat/lobby/. Open a second browser tab to the same room page.

In the second browser tab, type the message “hello” and press enter. You should now see “hello” echoed in the chat log in both the second browser tab and in the first browser tab.

Now your chat server is fully asynchronous!

This tutorial continues in Tutorial 4.

4 - Tutorial Part 4: Automated Testing

End-to-end tests for the chat server with Selenium and ChannelsLiveServerTestCase.

This tutorial begins where Tutorial 3 left off. We’ve built a simple chat server and now we’ll create some automated tests for it.

Testing the views

To ensure that the chat server keeps working, we will write some tests.

We will write a suite of end-to-end tests using Selenium to control a Chrome web browser. These tests will ensure that:

  • when a chat message is posted then it is seen by everyone in the same room
  • when a chat message is posted then it is not seen by anyone in a different room

Install the Chrome web browser, if you do not already have it.

Install Selenium as a development dependency, like the testing tools in the MDN tutorial, so that it is never installed on your production server. Run the following command:

uv add --dev selenium

Commit the updated pyproject.toml and uv.lock.

You don’t need to install chromedriver yourself. The first time the tests start Chrome, Selenium finds a matching chromedriver or downloads one automatically.

Create a new file chat/tests.py. Your app directory should now look like:

chat/
    __init__.py
    consumers.py
    routing.py
    templates/
        chat/
            index.html
            room.html
    tests.py
    urls.py
    views.py

Put the following code in chat/tests.py:

# chat/tests.py
from channels.testing import ChannelsLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait


class ChatTests(ChannelsLiveServerTestCase):
    serve_static = True  # emulate StaticLiveServerTestCase

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        try:
            # NOTE: Selenium finds or downloads a matching chromedriver automatically
            cls.driver = webdriver.Chrome()
        except:
            super().tearDownClass()
            raise

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()
        super().tearDownClass()

    def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self):
        try:
            self._enter_chat_room("room_1")

            self._open_new_window()
            self._enter_chat_room("room_1")

            self._switch_to_window(0)
            self._post_message("hello")
            WebDriverWait(self.driver, 2).until(
                lambda _: "hello" in self._chat_log_value,
                "Message was not received by window 1 from window 1",
            )
            self._switch_to_window(1)
            WebDriverWait(self.driver, 2).until(
                lambda _: "hello" in self._chat_log_value,
                "Message was not received by window 2 from window 1",
            )
        finally:
            self._close_all_new_windows()

    def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self):
        try:
            self._enter_chat_room("room_1")

            self._open_new_window()
            self._enter_chat_room("room_2")

            self._switch_to_window(0)
            self._post_message("hello")
            WebDriverWait(self.driver, 2).until(
                lambda _: "hello" in self._chat_log_value,
                "Message was not received by window 1 from window 1",
            )

            self._switch_to_window(1)
            self._post_message("world")
            WebDriverWait(self.driver, 2).until(
                lambda _: "world" in self._chat_log_value,
                "Message was not received by window 2 from window 2",
            )
            self.assertTrue(
                "hello" not in self._chat_log_value,
                "Message was improperly received by window 2 from window 1",
            )
        finally:
            self._close_all_new_windows()

    # === Utility ===

    def _enter_chat_room(self, room_name):
        self.driver.get(self.live_server_url + "/chat/")
        ActionChains(self.driver).send_keys(room_name, Keys.ENTER).perform()
        WebDriverWait(self.driver, 2).until(
            lambda _: room_name in self.driver.current_url
        )

    def _open_new_window(self):
        self.driver.execute_script('window.open("about:blank", "_blank");')
        self._switch_to_window(-1)

    def _close_all_new_windows(self):
        while len(self.driver.window_handles) > 1:
            self._switch_to_window(-1)
            self.driver.execute_script("window.close();")
        if len(self.driver.window_handles) == 1:
            self._switch_to_window(0)

    def _switch_to_window(self, window_index):
        self.driver.switch_to.window(self.driver.window_handles[window_index])

    def _post_message(self, message):
        ActionChains(self.driver).send_keys(message, Keys.ENTER).perform()

    @property
    def _chat_log_value(self):
        return self.driver.find_element(
            by=By.CSS_SELECTOR, value="#chat-log"
        ).get_property("value")

Our test suite extends ChannelsLiveServerTestCase rather than Django’s usual suites for end-to-end tests (StaticLiveServerTestCase or LiveServerTestCase) so that URLs inside the Channels routing configuration like /ws/chat/ROOM_NAME/ will work inside the suite.

We are using sqlite3, which for testing is run as an in-memory database, and therefore the tests will not run correctly. We need to tell our project that the test database should be a file instead. Edit the DATABASES setting in locallibrary_config/settings.py and add a TEST entry, keeping the ENGINE and NAME lines you already have:

# locallibrary_config/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
        'TEST': {
            'NAME': BASE_DIR / 'test_db.sqlite3',
        },
    }
}

Django creates test_db.sqlite3 while the tests run, and it should never be committed. If you started your .gitignore from GitHub’s Python template, its *.sqlite3 line already ignores it. Otherwise, add this line:

test_db.sqlite3

The tests use your real channel layer, so Redis must be running (see Part 2). To run the tests, run the following command:

uv run python manage.py test chat.tests

You should see output that looks like:

Creating test database for alias 'default'...
Found 2 test(s).
System check identified no issues (0 silenced).
Not Found: /favicon.ico
..
----------------------------------------------------------------------
Ran 2 tests in 8.953s

OK
Destroying test database for alias 'default'...

Chrome windows will open and close by themselves while the tests run. The Not Found: /favicon.ico line is Chrome asking for an icon the chat pages don’t have; you can ignore it.

You now have a tested chat server!

What’s next?

Congratulations! You’ve fully implemented a chat server, made it performant by writing it in asynchronous style, and written automated tests to ensure it won’t break.

This is the end of the tutorial. At this point you should know enough to start an app of your own that uses Channels and start fooling around. As you need to learn new tricks, come back to the rest of the Channels documentation.