Cassidy
Cassidy

Reputation: 3408

Refreshing images on a page without refreshing the whole page with Django

I'm making an application that receives images.

I'm making it in a pretty hacky way, where this is the HTML:

<body onload="javascript:setTimeout('location.reload(true);', 1000);" >
<div class="container">
  <img class="img0" src="{{ uno }}"/>
  <img class="img1" src="{{ dos }}"/>
  <img class="img2" src="{{ tres }}"/>
</div>
</body>

And this is in views.py:

def main(request):
  x = get_newest_pics()

  uno = x[-1]
  dos = x[-2]
  tres = x[-3]

  context = { 'uno' : uno, 'dos' : dos, 'tres' : tres }

  return render(request, 'index.html', context)

I'm sure there's a better way to go about this, but I'm very new to Django and I don't know how. At this point, the page is just flickering every second showing the same images, when really I just want it to refresh whenever there is a new image. Is there a way to consistently call get_newest_pics() and refresh just the images, rather than the whole page? Or even just a way to make the page stop flickering?

Upvotes: 0

Views: 404

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

The way to do this is to implement ajax on your front end, and then request for new images at an interval, once a new image is found, update the container where you are showing your images and add the new (available) image.

Have a look at the django-dajaxice library to help you with the "wiring" of your front end to django correctly.

The way you have written your code, all three images are sent at once to your page, and your javascript snippet is in effect just refreshing the page very quickly, which is why you see the flickering effect.

You could do a "hack" and create a separate view for each image in django, then call each view on an interval using javascript - it would have the same end result but really inefficient in terms of code.

Upvotes: 1

Related Questions