Skip to content

HTMX websockets extension doesn’t connect to Django channels

I try to connect a Django channels Consumer to a HTMX ext-ws element, but I can’t get a step further.

class MessageConsumer(WebsocketConsumer):
    def connect(self):
        #    "type": "websocket.send",
        #    "text": "..."
  <script src="{% static 'common/js/htmx/htmx.min.js' %}" defer></script>
  <script src="{% static 'common/js/htmx/ext/ws.js' %}" defer></script>

The HTMX.js and the ws.js gets loaded correctly at the client’s browser.

<div id="messages-container"
  {# hx-ext="ws" ws-connect="/ws/messages/" does not work at all #}
  <div id="message"></div>

If I use the old HTMX-builtin hx-ws method, at least the websocket connects. But I can’t get a message to the HTMX element (I thought the #message div should be replaced).

If I use the new-style (HTMX extension) syntax (hx-ext="ws" ws-connect...)

Can anyone point me to the right direction?



As per docs you need to also include hx-swap-oob="true" attribute into the html that you send back from websocket:

See example from htmx GH:

When using the plugin version, what worked for me was removing the defer attribute from htmx related script tags. Not sure why including defer is causing the issue though.


A GH issue has been opened by OP:

5 People found this is helpful