【发布时间】:2022-01-20 21:42:45
【问题描述】:
我有一个模型,并且在一个函数中这个模型正在更新。 我想动态显示这个模型的数据。因此,应该在不刷新页面的情况下显示新值。我该怎么做?
models.py
class MyLongProcess(models.Model):
active_uuid = models.UUIDField('Active process', null=True, blank=True)
name = models.CharField('Name', max_length=255)
current_step = models.IntegerField('Current step', default=0)
total = models.IntegerField('Total', default=0)
@property
def percentage_sending(self):
# or it can be computed by filtering elements processed in celery with complete status
return int((current_step / total) * 100)
views.py
def setup_wizard(request):
process = MyLongProcess.objects.create(active_uuid=uuid.uuid4(), name=name, total=100)
functions.myClass(..., process=process)
....
return render(request, 'setup_wizard.html', context)
functions.py
class myClass():
def __init__(self, ..., process):
self.download_all(..., process=process)
@app.task(bind=TRUE)
def download_all(self, ..., process):
....
for s in scans:
....
process.current_step += 1
process.save()
...
setup_wizard.html
<div class="progress-bar" role="progressbar"
style="width: {{ my_model_object.percentage_sending }}%;"
aria-valuenow="{{ my_model_object.percentage_sending }}"
aria-valuemin="0" aria-valuemax="100">{{ my_model_object.percentage_sending }}%
</div>
我的所有功能都可以正常工作。当我从 Django 管理员查看 MyLongProcess 并刷新页面时,值正在更新。只是我想在前端显示而不刷新。
【问题讨论】:
-
你考虑过
django-channels吗?设置加载管理页面时要连接的频道,您可以在后端向任何连接的人广播数据。 -
@Lewis 我以前从未听说过。我会研究它
标签: javascript python html django ajax