How to use django channels with htmx / Channels /

Introduction

In a previous post, we setup a simple echo application using Django Channels. In this post, we will extend that application to use htmx.

htmx is a library that allows you to access AJAX, WebSockets, and Server Sent Events directly in your HTML.

Modifying the template

We'll load htmx and the required Websocket Extension via a CDN and update our template to use htmx. Replace the contents of index.html with the following:

<!DOCTYPE html>
<html>
<head>
    <title>Echo</title>
</head>
<body hx-ext="ws" ws-connect="/ws/echo/">
    <h1>Echo Test</h1>

    <!-- Specify the target for the response -->
    <span id="reply"></span>

    <!-- Attach ws-send to a form -->
    <form ws-send>
        <input type="text" name="message">
        <button type="submit">Send</button>
    </form>

    <script src="https://unpkg.com/htmx.org@2.0.3"></script>
    <script src="https://unpkg.com/htmx-ext-ws@2.0.1/ws.js"></script>
</body>
</html>

We will also need to modify the consumer in core/consumers.py to deliver the message in hypertext.

import json

from channels.generic import websocket


class EchoConsumer(websocket.WebsocketConsumer):
    def receive(self, text_data):
        json_data = json.loads(text_data)
        message = json_data['message']
        response = f'<span id="reply">{message}</span>'
        self.send(text_data=response)

How it works?