在Django中刷新模板 [英] Refresh template in Django
问题描述
我有这样的看法:
def form1(request):
if request.method == 'POST':
form = SyncJobForm(request.POST)
if form.is_valid():
# do something
in_progress = True
return render_to_response('form1.html', {'in_progress': in_progress})
我想知道如何设置刷新模板后,完成了视图进程。就像渲染页面一样:
I would like to know how to set it to refresh the template after is done with the view process. Like rendering the page after its done:
in_progress = True
return render_to_response('form1.html', {'in_progress': in_progress})
# after its finished
finished = True
return render_to_response('form1.html', {'finished': finished})
如何实现这样的东西?感谢提前。
How can I implement something like this? Thanks in advance.
推荐答案
您无法在全球范围内维护页面调用之间的状态,因此您需要存储你的数据在数据库中。此外,视图在返回页面后无法与浏览器协商,因此您需要将其拆分为多个视图,并为作业生成单独的线程。以下是一般的大纲,可能有助于:
You can't maintain state between page calls on a global basis, so you'll need to store your data in the database. In addition, a view can't negotiate anything with the browser after it has returned a page, so you need to split this into multiple views and spawn a separate thread for the job. Here's a general outline that might help:
def do_something():
my_job = Jobs.get(id=blah)
my_job.in_progress = True
my_job.save()
# Do some stuff here....
my_job.in_progress = False
my_job.save()
def step1(request):
in_progress = Jobs.get(id=blah).in_progress
if not in_progress:
if request.method == 'POST':
form = SyncJobForm(request.POST)
if form.is_valid():
thread.start_new_thread(do_something)
return HttpResponseRedirect(step2)
else:
return render_to_response('form.html', 'form': form)
else:
form = SyncJobForm()
return render_to_response('form.html', 'form': form)
else:
return HttpResponseRedirect(step2)
def step2(request):
in_progress = Jobs.get(id=blah).in_progress
if in_progress:
return render_to_response('in_progress.html')
else:
return HttpResponseRedirect(finished)
def finished(request):
return render_to_response('finished.html')
然后让您的页面 in_progress.html
定期刷新页面。作业完成后,您可以在 finished.html
中显示状态消息。
Then have your page in_progress.html
periodically refresh the page. When the job is completed, you can display a status message in finished.html
.
有更复杂的方法要做到这一点(写入Javascript来定期轮询服务器),但是您仍然需要编写单独的视图来响应适当的信息。此外,您可以使用 Celery 等工作管理框架来创建和执行工作,但再次仍然需要创建单独的视图来处理状态信息。
There are more sophisticated ways to do this (write Javascript to poll the server periodically), but you're still going to need to write separate views to respond with the appropriate information. In addition, you could use a job management framework like Celery to create and execute jobs, but again you'll still have to create separate views to handle status information.
这篇关于在Django中刷新模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!