[Answer]-Django-printing of random values

1👍

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:

views.py

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

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

urls.py

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

Then in your template:

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

window.setTimeout(refreshRandom, 5000);
</script>
<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.

👤yuvi

0👍

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);
    $('#random-number').text(random_number);
}, 5000); // every 5 second

Leave a comment