如何在django模板中每秒更新照片?

时间:2019-01-16 09:56:15

标签: django django-templates

每个人。我对django很陌生。 在我的django模板中有一个特定位置显示照片,并且应该每秒更新照片。我怎样才能做到这一点? (新照片的路径来自数据库。我知道如何从数据库获取它们。) 我只知道如何通过url请求返回html,但是如何在没有新url请求的情况下更新该html中的特定项目?

更多信息:必须显示的照片是由另一个过程实时生成的,因此照片的路径也是如此。

实际上,我还没有实现它。我仍在学习django,但可以通过以下简单代码来模拟这种情况:

urls.py:

urlpatterns = [ url(r'^hello/$', hello_world),]

views.py:

from django.shortcuts import render
from datetime import datetime

def hello_world(request):
    return render(request, 'hello_world.html', {
        'current_time': str(datetime.now()),
    })

hello_world.html:

<!-- hello_world.html -->

<!DOCTYPE html>
<html>
    <head>
        <title>I come from template!!</title>
        <style>
            body {
               background-color: lightyellow;
            }
            em {
                color: LightSeaGreen;
            }
        </style>
    </head>
    <body>
<script>
    setInterval(function() {
        fetch("{% url 'hello_ajax' %}").then(function (response) {
    var current_time = response.json().current_time;
    console.log(current_time);
    document.getElementById("test").innerHTML = current_time;
        });
    }, 1000);
</script>
        <h1>Hello World!</h1>
    <em id="test"></em>
    </body>
</html>

我们可以通过刷新页面来更新current_time,但是每秒更新current_time而不刷新页面又如何呢?我们可以将照片视为当前时间来模拟我的情况。

更新: 终于成功了:

<script>
    setInterval(function() {
        fetch("{% url 'hello_ajax' %}").then(response => response.json())
.then(data => {
    // you can access your data here
    document.getElementById("test").innerHTML = data.current_time;
});
    }, 1000);
</script>

我想知道为什么它不起作用:

<script>
        setInterval(function() {
            fetch("{% url 'hello_ajax' %}").then(response =>{
        // you can access your data here
        document.getElementById("test").innerHTML = response.json().current_time;
    });
        }, 1000);
</script>

它表示“(index):22未捕获(承诺中)TypeError:无法在'Response'上执行'json':主体流锁定在fetch.then.data上” 有想法吗?

1 个答案:

答案 0 :(得分:0)

不幸的是,您只能使用某些JavaScript(例如setTimeout)来实现它。如果清单不大,您可以将其呈现到JavaScript数组,然后使用例如setTimeout切换照片。 这不是最好的主意(我什至还记得读过一些有一定道理的文章,说明它为什么不好,会尝试找到它),但是会去做。 因此,您可以在模板的正文末尾执行以下操作:

<script>
    arrayOfUrls = [
        {% for url in urls}"{{ url }}",{% endfor %}
    ];
    function switchPhoto(urlArray, switchTo) {
        // if to go back to 0 if array finished
        document.getElementById("your-photo-id").src = urlArray[switchTo];
        setTimeout(switchPhoto, 1000, urlArray, switchTo + 1);
    }
    switchPhoto(arrayOfUrls, 0);
</script>

更新后: 如果您不想刷新页面,则解决方案可能是以下方法:

views.py

from django.http import JsonResponse
def hello_world(request):
    return render(request, 'hello_world.html', {
        'current_time': str(datetime.now()),
    })

def hellow_world_ajax(request):
    return JsonResponse({'current_time': str(datetime.now())})

url(r'^hello_ajax/$', hellow_world_ajax, name="hello_ajax"),添加到urls.py

然后在模板主体中使用以下代码编写JavaScript:setInterval和普通JS fetch或某些js库/框架插入定期更新逻辑:

<script>
    setInterval(function() {
        fetch("{% url 'hello_ajax' %}").then(function (response) {
            document.getElementById("your-photo-id").src = response.json().current_time;
        });
    }, 1000);
</script>