G
G
Gourii2020-12-03 11:31:16
Django
Gourii, 2020-12-03 11:31:16

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.

test_update.html

<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>


A piece of views.py

def test(request):
    tmem = {}
    tmem["mfree"] = bytes2human(psutil.virtual_memory()[4])
    tmem["tfree"] = str(datetime.datetime.now())
    return render(request, 'test_update.html', tmem)


The test page opens and the data is displayed, BUT the automatic update of the data does not work.

5fc8a1be21f74790676614.png

Please tell me what I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Belokurov, 2020-12-03
@kyern

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 question

Ask a Question

731 491 924 answers to any question