最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reload the table without refreshing the page in Django - Stack Overflow

programmeradmin0浏览0评论

Have small table that needs to be updated every 10 seconds with new data. Entire website is working in Django. JSON is parsing data into 1 table and rewriting the data every 10 seconds in database. The website is showing the data from the database. The procedure I need is to refresh the front-end table with new data every 10 seconds - it would be the AJAX I assume, can you help me write the code for it? It would not append data to the table, just keep refreshing it.

Example - The table in the database has fixed 10 rows of data and it is being refreshed by JSON. The front-end would always show 10 rows, so every 10 seconds, the table (front-end) would always show 10 rows with the new data.

Django version 1.11

Here are the python files

views.py

def prices(request):
    prices = Price.objects.all().order_by('id')
    return render(request, 'prices.html', {'prices':prices})

prices.html

<div class="col-md-8">
     <table class="table table-striped">
         <thead>
             <tr>
                 <th>TYPE</th>
                 <th>NAME</th>
                 <th>PRODUCT</th>
                 <th>VALUE</th>                 
             </tr>
         </thead>
         <tbody>
         {% for price in prices %}
             <tr>
                 <td>{{ price.type }}</td>
                 <td>{{ price.name }}</td>
                 <td>{{ price.product }}</td>
                 <td>{{ price.value }}</td>
             </tr>
         {% endfor %}
         </tbody>
     </table>
 </div>

urls.py

urlpatterns = [
     url(r'^prices/', product_views.prices, name='prices'),
     url(r'^admin/', admin.site.urls),
]

Have small table that needs to be updated every 10 seconds with new data. Entire website is working in Django. JSON is parsing data into 1 table and rewriting the data every 10 seconds in database. The website is showing the data from the database. The procedure I need is to refresh the front-end table with new data every 10 seconds - it would be the AJAX I assume, can you help me write the code for it? It would not append data to the table, just keep refreshing it.

Example - The table in the database has fixed 10 rows of data and it is being refreshed by JSON. The front-end would always show 10 rows, so every 10 seconds, the table (front-end) would always show 10 rows with the new data.

Django version 1.11

Here are the python files

views.py

def prices(request):
    prices = Price.objects.all().order_by('id')
    return render(request, 'prices.html', {'prices':prices})

prices.html

<div class="col-md-8">
     <table class="table table-striped">
         <thead>
             <tr>
                 <th>TYPE</th>
                 <th>NAME</th>
                 <th>PRODUCT</th>
                 <th>VALUE</th>                 
             </tr>
         </thead>
         <tbody>
         {% for price in prices %}
             <tr>
                 <td>{{ price.type }}</td>
                 <td>{{ price.name }}</td>
                 <td>{{ price.product }}</td>
                 <td>{{ price.value }}</td>
             </tr>
         {% endfor %}
         </tbody>
     </table>
 </div>

urls.py

urlpatterns = [
     url(r'^prices/', product_views.prices, name='prices'),
     url(r'^admin/', admin.site.urls),
]
Share Improve this question edited Apr 23, 2017 at 17:15 Radek asked Apr 23, 2017 at 17:01 RadekRadek 1,1893 gold badges22 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Create a django view that returns all rows in the specified table. Now create a ajax function that polls the django view (via a url) every 10 seconds.

Use jquery, you would have to include jquery cdn like this :

<script src="https://ajax.googleapis./ajax/libs/jquery/3.2.0/jquery.min.js">

Now the ajax function (jquery ajax)

var updateTable = $.ajax({

                method: "GET",
                url: "prices/",


                success: function(data, textStatus, request) {

                console.log(data) 
                //update your DOM with new data recieved in **data**

            }
        });

setInterval(updateTable,10000);

Execute this ajax function every 10 seconds. Remember that the view will return raw html with the table. This data will be accessible in success callback function of the ajax function you wrote. Now you would have to update your DOM with the new table you got in data variable. Try to run console.log(data) from inside success callback to see the response by server.

I have acplished this with Django REST Framework and AJAX with a hint above. Was not sure how to do it in the views so I used REST. By using REST I have JSON to use for AJAX. The previous answer is refreshing entire page, this one is refreshing the table in the front-end.

I cannot say if this it the best solution, but it is working great. Maybe there is a much faster one.

API

serializers.py

from rest_framework import serializers
from .models import Price

class PriceModelSerializer(serializers.ModelSerializer):
     class Meta:
         model = Price
         fields = [
             'type',
             'name',
             'product',
             'value',
         ]

views.py for API

 from rest_framework import generics
 from .serializers import PriceModelSerializer
 from .models import Price

 class PriceListAPIView(generics.ListAPIView):
      serializer_class = PriceModelSerializer

     def get_queryset(self):
          return Price.objects.all().order_by('sort')

urls.py for API

 urlpatterns = [
     #...other urls
     url(r'^$', PriceListAPIView.as_view(), name='list'),
 ]

template

 <section class="pt100 pb100">
     <div class="container">
          <div class="vertical-align">
              <div class="col-md-12">
                  <table class="table table-striped">
                       <thead>
                            <tr>
                                 <th>TYPE</th>
                                 <th>NAME</th>
                                 <th>PRODUCT</th>
                                 <th>VALUE</th>
                            </tr>
                       </thead>
                       <tbody>

                       </tbody>
                  </table>
              </div>
          </div>
      </div>
 </section>

main urls.py

 urlpatterns = [
     #...other urls
     url(r'^api/prices/', include('[LOCATION_OF_YOUR_URLS].urls', namespace='api-prices')),
 ]

AJAX

 <script>

    setInterval(function() {
        $.ajax({
            method: "GET",
            url: "/api/prices/",
            success: function(data) {
                $("tbody").empty();
                $.each(data, function (key, value) {
                    var priceKey = key;
                    var priceType = value.type;
                    var priceName = value.name;
                    var priceProduct = value.product;
                    var priceValue = value.value;
                    $("tbody").append(
                       "<tr><td>" + priceType + "</td><td>" + priceName + "</td><td>" + priceProduct + "</td><td>" + priceValue + "</td></tr>"
                    )
                })
            },
            error: function(data) {
                console.log("error")
                console.log(data)
            }
        })
    }, 1000)
 </script>
发布评论

评论列表(0)

  1. 暂无评论