I am developing a code in Django and trying to refresh the table automatically. I have used jquery but it does not refresh the table. Here is the my view: (views.py)
from django.http import HttpResponse
from django.template import loader
from models import objectDB
def index(request):
objects= objectDB.objects.all()
template = loader.get_template('Myapp/index.html')
context= { 'objects': objects}
return HttpResponse(template.render(context, request))
def refreshedindex(request):
increment = int(request.GET['increment'])
increment_to = increment + 10
objects= objectDB.objects.all()
template = loader.get_template('Myapp/refreshedindex.html')
context= {'objects': objects}
return HttpResponse(template.render(context, request))
Here is my table plus java script: (index.html)
<style>
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even){background-color: #f2f2f2;}
#customers tr:hover {background-color: #ddd;}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
{% if objects %}
<table style="width:100%" border="1" id = "customers">
<tr>
<th>obj Value</th>
<th>item</th>
<th>Type</th>
<th>Tags</th>
<th>Date First</th>
<th>Date Last</th>
</tr>
{% for obj in objects %}
<tr>
<td>{{ obj.value }}</td>
<td>{{ obj.item }}</td>
<td>{{ obj.type }}</td>
<td>{{ obj.tags }}</td>
<td>{{ obj.date_first }}</td>
<td>{{ obj.date_last }}</td>
</tr>
{% endfor%}
</table>
{% else %}
<h3>These is no obj to show</h3>
{% endif %}
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'refreshedindex' %}, // URL to your view that serves new info
data: {'append_increment': append_increment}
})
.done(function(response) {
$('#customers').append(response);
append_increment += 10;
});
}, 10000)
</script>
The following is the code the need to be used when the page will be updates (refreshedindex.html)
{% for obj in objects %}
<tr>
<td>{{ obj.value }}</td>
<td>{{ obj.item }}</td>
<td>{{ obj.type }}</td>
<td>{{ obj.tags }}</td>
<td>{{ obj.date_first }}</td>
<td>{{ obj.date_last }}</td>
</tr>
{% endfor%}
And this is the code of url.py.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name= 'index'),
url(r'^$', views.refreshedindex, name= 'refreshedindex'),
]
I have tried to fix the problem but I have no clue what is wrong here. Can you help me on solving this problem?