Skip to content
Advertisement

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):
        self.accept()
        print("connect")
        #self.send( 
        #    "type": "websocket.send",
        #    "text": "..."
        #)
...
<head>
...
  <script src="{% static 'common/js/htmx/htmx.min.js' %}" defer></script>
  <script src="{% static 'common/js/htmx/ext/ws.js' %}" defer></script>
...
</head>
...

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

<div id="messages-container"
     hx-ws="connect:/ws/messages/" 
  {# hx-ext="ws" ws-connect="/ws/messages/" does not work at all #}
    
>
  <div id="message"></div>
</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?

Advertisement

Answer

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: https://github.com/bigskysoftware/htmx/blob/master/test/servers/ws/server.go#L24

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.

Update:

A GH issue has been opened by OP: https://github.com/bigskysoftware/htmx/issues/957

5 People found this is helpful
Advertisement