Praful Bagai
Praful Bagai

Reputation: 17392

Django-printing of random values

I want that the random number generated should be printed on the webpage, ie via HttpResponse(x) after every 5 seconds, for which I have used the time.sleep function.

How do I print the randomly generated values without refreshing the page?

Here is my view.py file

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

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

Urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',

    url(r'random/','apps.graph.views.main', name = 'graph_home'),
    url(r'random_gen/','apps.graph.views.random_generator', name = 'random'),
)

Template

<!DOCTYPE html>
<html>
    <head>
        <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>    
    </head>

    <body>
        <div id='random'></div>
    </body>
</html>

Upvotes: 0

Views: 219

Answers (2)

yuvi
yuvi

Reputation: 18437

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.

Upvotes: 1

Hieu Nguyen
Hieu Nguyen

Reputation: 8623

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

Upvotes: 0

Related Questions