Reload table data in Django without refreshing the page

You can use setInterval, jQuery AJAX, and a view:

Your HTML

   <table id="_appendHere" class="table table-striped table-condensed">
      <tr>
        <th>Reg.nr.</th>
        <th>M&auml;rke</th>
        <th>Modell</th>
      </tr>
      {% for i in order %}
        {% if i.order_booked %}
        <tr class="success">
        {% else %}
        <tr>                    
        {% endif %}

         <td>{{ i.regnr|upper }}</td>
         <td>{{ i.brand|capfirst }}</td>
         <td>{{ i.brand_model|capfirst }}</td>
      </tr>
      {% endfor %}
    </table>

JS

<script>
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% url 'get_more_tables' %},  // URL to your view that serves new info
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 10000)
</script>

View

def get_more_tables(request):
    increment = int(request.GET['append_increment'])
    increment_to = increment + 10
    order = Order.objects.filter(owner=request.user).order_by('-id')[increment:increment_to]
    return render(request, 'get_more_tables.html', {'order': order})

get_more_tables.html

  {% for i in order %}
  <tr>
    {% if i.order_booked %}
    <tr class="success">
    {% else %}
    <tr>                    
    {% endif %}

     <td>{{ i.regnr|upper }}</td>
     <td>{{ i.brand|capfirst }}</td>
     <td>{{ i.brand_model|capfirst }}</td>
  </tr>
  {% endfor %}

And then just make sure to add the new view into your urls.py (make sure it has name="get_more_tables", or whatever the name is in your JS url:)

What this does is use setInterval, a JS function, to make a GET AJAX request every 10000ms (10 seconds) to a view in your server. The view then renders a separate HTML file using this new context, and sends it as a response back to your original HTML page. The new response is then appended via jQuery to your table. Every time this cycle happens, the slice is incremented, so you don’t get the same results from Order.

Keep in mind that this will loop non-stop, so if you want it to end you will have to add code to the JS to stop setInterval if the last response came back empty.

Leave a Comment