How can i update a django template in real time?

自闭症网瘾萝莉.ら 提交于 2020-08-25 03:46:28

问题


In this template i'm retrieving the price of Bitcoin from an API. At the actual moment, the price will be updated only when the page is refreshed, while i would like it to be updated without refreshing the whole page, dynamically.

This is my view:

def home(request):

    symbol = "BTCUSDT"
    tst = client.get_ticker(symbol=symbol)

    test = tst['lastPrice']

    context={"test":test}

    return render(request,
                  "main/home.html", context
                  )

And the template's line looks something like this:

<h3> var: {{test}} </h3> 

There are two problems here:

1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page.

2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true in the view, but of course it broke my code, executing only the part the while statement.

Any advice is appreciated :)


回答1:


You should separate your frontend and backend in order to dynamically update the DOM contents without needing to render the whole DOM each time.

The responsibility of frontend would be to request and fetch the latest values when a user does an action that warrant a refresh or fetching of updated data. The request need to made asynchronously via e.g. AJAX. The newer JS frameworks e.g. React, Vue use virtual DOM that use an intermediate virtual DOM that they use to push the updates and finally update the real DOM in a single go; which makes them very performant.

The (Django) backend should expose an API that would take (AJAX) requests from backend for specific resources, and serve them.

A nice framework for Django is DRF (Django REST Framework), which exposes REST endpoints that you can call from frontend via AJAX and get reponse back so that the frontend can do necessary updates.

This is a failrly high level view, and is written to give you an idea that you can implement by digging deeper.



来源:https://stackoverflow.com/questions/56805630/how-can-i-update-a-django-template-in-real-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!