Django-channels consumer.py to display a table.py from django-table2 in a template in Django

I am using Django-channels to make a Realtime table, but I have no idea how to write my consumer.py to display the django-tables2 table in my template.

I read the docs, but they only have chat examples

consumer.py
class RealTimeTable(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()
        await self.send(text_data=json.dumps({
            'message': 'Connected'
        }))

    async def disconnect(self, close_code):
        await self.send(text_data=json.dumps({
            'message': 'Disconnected'
        }))

    async def receive(self, text_data):
        table = ParticipantTable(Participant.objects.all())
        rendered_table = table.as_html()

        await self.send(text_data=json.dumps({
            'tables': rendered_table
        }))

display.html
<div id="table-container"></div>

<script>

  var socket = new WebSocket("ws://" + window.location.host + "/ws/socket-sever/");
            
  socket.onmessage = function(e) {
    var data = JSON.parse(e.data);
    console.log(data.html);
    document.querySelector('#table-container').innerHTML = data.html;
};

  
  socket.onclose = function(event) {
      console.error("WebSocket closed with code: " + event.code);
  };

</script>

Fundamentally, there’s not a whole lot of difference between the two.

If you think about what the chat example is doing on the client side, it’s receiving some text being sent to it, and updating the current page. In this case, it’s adding the text to a div.

If you’re rendering a complete table, and you send the html for that table through the connection, then the client will add that text to a div.

So there’s no functional difference in the client for the basic case.

Now, when you want to have different things being updated, you need to have your JS examine the data being returned to determine what should be done, but that’s not a significant conceptual difference.

On the server side, again - there’s no conceptual difference here. In the chat example, the consumer receives text, and turns around and sends that text back out. In your tables example, the consumer would receive whatever message it needs to receive, render the html for the table, and send that back out to the client.

So the infrastructure doesn’t change. You’re adding functionality to the chat app, not replacing it.

Side note: I strongly encourage you to take a look at HTMX for handling websockets. It was a game-changer for me. There are so many things it makes so much easier.

1 Like

May you point me in a direction in the HTMX docs that can help me with my real time table problem.

I just don’t know where to start with HTMX. As I tried using it, but had many problems with it

What issue(s) are you having with HTMX? Are they related to HTMX in general or HTMX with websockets in particular?

I’m not actually aware of much in the way of tutorials for HTMX, I learned it by working my way through the docs.

The problems are with HTMX in general. My issues are getting the page to update with my Pagination of my table applied

I have not even started on HTMX WebSocket, I will be reading up on that now

If you’ve ever worked with AJAX - particularly with jQuery, a lot of the concepts transfer really well.

If not, there are just a couple key concepts to keep in mind, and they’re summarized right on the home page.

  • Using the hx-get attribute, any html element can issue an http get.
  • By default, what is retrieved from the server replaces the innerHTML of the element that triggered the get.

As far as Django is concerned, nothing really changes due to HTMX - at least as compared to any other AJAX interface. The http get causes a view to be executed. That view needs to return the html fragment to fill the intended element.

Everything beyond that are just extensions of this. As long as you keep these fundamentals in mind, it’s really easy to work with.

Was this related to your thread from a couple weeks ago or something else?

I’ve never thought about using the Django Paginator with HTMX. They probably work really well together.

1 Like

Hi, I’m stuck in the same problem, have you found any solution for this?

I’m using HTMX and django_tables2 but I can’t pass the request object to the websocket message.

That’s because there isn’t a “request” in a websocket. A websocket is a persistent connection and does not create or use a request for each frame of data being transferred.