Answer the question
In order to leave comments, you need to log in
How do I set up automatic data updates in a Django template using Ajax?
Hello!
I'm trying to figure out how to automatically update data on a Django test site. I read the information on Ajax and this is what I could come up with as a test case.
<html>
<head>
<title>Test Update Data</title>
<script type="text/javascript">
$(function getnewdata(){
$.ajax({
url: '*.*.*.*:8000/test',
type: 'get',
success: function(data) {
alert(data);
}
});
})
$(document).ready(function(){
setInterval(getnewdata,1000);
});
</script>
</head>
<body>
<p>{{ mfree }}</p>
<p>{{ tfree }}</p>
</body>
</html>
def test(request):
tmem = {}
tmem["mfree"] = bytes2human(psutil.virtual_memory()[4])
tmem["tfree"] = str(datetime.datetime.now())
return render(request, 'test_update.html', tmem)
Answer the question
In order to leave comments, you need to log in
You give back the template.
You either need to create a separate URL that will process the AJAX request and return only data, for example, in JSON format, or pass additional parameters when requesting, for example, in GET ajax=1, process this parameter separately in the view and also return only values, not render template.
Then your handler on the page, after receiving the data, replaces them on the page.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question