[Answer]-Django-printing of random values


You create a view for the main page, and another view that returns a random number. Then you write an ajax call in javascript to refresh what you see. Like this:


def main(request):
    return render(request, 'index.html')

def random_generator(request):
    return HttpResponse(randrange(0, 5))


url('^main/$', 'myapp.views.main'),
url('^random/$', 'myapp.views.random_generator')

Then in your template:

<script type="text/javascript">
function refreshRandom() {
        url: '/random/',
        dataType: 'html',
        success: function(data) {
        complete: function() {
            window.setTimeout(refreshRandom, 5000);

window.setTimeout(refreshRandom, 5000);
<div id='random'></div>

Though I don’t really see what would you gain by doing this through a django view. If that’s all you want to do, you might want to try and write the whole thing on the client side with javascript.



You can use pure JS to achieve it, no need to bother Django:

var random_interval = setInterval(function() {
    var random_number = 1 + Math.floor(Math.random() * 6);
}, 5000); // every 5 second

Leave a comment