简体   繁体   English

刷新页面上的图像而无需使用Django刷新整个页面

[英]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: 我正在以一种非常怪异的方式来实现它,这就是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 : 这是在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. 我敢肯定有更好的方法可以解决这个问题,但是我对Django很陌生,我也不知道怎么做。 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? 有没有办法一致地调用get_newest_pics()并仅刷新图像,而不刷新整个页面? Or even just a way to make the page stop flickering? 甚至只是一种使页面停止闪烁的方法?

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. 这样做的方法是在前端实现ajax,然后每隔一段时间请求新图像,一旦找到新图像,请更新用于显示图像的容器并添加新(可用)图像。

Have a look at the django-dajaxice library to help you with the "wiring" of your front end to django correctly. 看一下django-dajaxice库,以帮助您正确地将前端“接线”到django。

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. 您编写代码的方式,所有三个图像都立即发送到您的页面,并且您的javascript代码段实际上只是非常快速地刷新页面,这就是您看到闪烁效果的原因。

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. 您可以执行“ hack”操作,并为django中的每个图像创建一个单独的视图,然后使用javascript在一个间隔上调用每个视图-最终结果相同,但代码效率很低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM