Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.6K
Visualizações
Reload the table without refreshing the page in Django

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),
]
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I have accomplished 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>
about 4 years ago · Santiago Trujillo Relatório

0

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.com/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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda