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
- [Answer]-Populate formset with information from db
- [Answer]-Can Django user model inheritance and abstract class be used in combination?
- [Answer]-Django 1.7 'AnonymousUser' object has no attribute 'backend'
- [Answer]-Why is Django (./manage runserver) serving files I've deleted?
- [Answer]-Django cannot find fandjango template (the application is installed)
Source:stackexchange.com