简体   繁体   中英

How to refresh a table in template of Django

I am currently obtaining an object from my views and displaying it in the template in form of a table. Currently I am struck at the part that we need to refresh the table/div, without refreshing the page.

In my views.py

def foo(request):
  testruns......
  render_to_response('pages/bar.html', locals(), context_instance=RequestContext(request))

My bar.html (template)

<div id = "roman">
    {% for trun in testruns %}

        <tr>
            <td>{{ trun.testprofile }}</td>
            <td>{{ trun.time }}</td>
            <td>{{ trun.testresult }}</td>
            <td>{{ trun.state }}</td>
        </tr>
    {% endfor %}
</div>

There are two approaches which are supposed to work:

  • Using dajaxice
  • Using [Jquery]

     $.ajax({ url: '{% url myview %}', success: function(data) { $('#the-div-that-should-be-refreshed').html(data); } });

I would like to know which approach is more suitable to my case. Using Approach 2, would the table auto refresh, and how do we set the time to refresh ?

Both acceptable but disadvantages of the second approach(pulling table from django as html ):

  1. Carried data over network is much bigger

  2. If u use something javascript based components in your table (maybe dojo based buttons etc.) they may cause some problems. I had a smilar issue in dojo and i found the solution in make dojo reparse the applied html. But life could not be easy everytime so first approach is better.

If this is only place where you need an auto-refresh, your approach 2 should work along with setting a timer to do the auto-refresh. You can use the setInterval function for the purpose:

// Refresh the Table every 5 seconds
setInterval(function(){
    $.ajax({    
       url: '{% url myview %}',
          success: function(data) {
          $('#the-div-that-should-be-refreshed').html(data);
          }
    });
}, 5000)

But if you are planning on developing a responsive webpage, where the whole UI needs to be kept updated, then I would suggest to use a full fledged framework like ember.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM