Django AJAX成功上的渲染模板

时间:2018-06-21 06:19:42

标签: ajax django

我正在尝试创建一个基于Django的Web应用程序,该应用程序需要用户输入并执行“重载”后台任务,该任务将在五到十分钟内完成。后台任务完成后,很少的参数会提供给模板进行渲染。一切正常,然后页面加载。

但是当我试图为此使用AJAX时,由于后台处理繁重,页面加载时间过长似乎并不好,我无法弄清楚如何重新加载页面(尽管我能够在完成时显示警报,但我想重新渲染页面)

这是我的views.py代码:

@Component
public class AdminUtil {

    private static IAirportService airportService;

    @Autowired
    public AdminUtil(IAirportService portService) {
        AdminUtil.airportService = portService;
    }

    ...

 }

这是我的AJAX通话

def index(request):
    #All Background process code goes here
    return render(request, 'form.html', {'scanResults' : scanResults, 'context_list' : context_list, 'scanSummary' : scanSummary})

我无法弄清楚,我应该在成功函数中写些什么来重新加载索引函数返回到模板的页面。

我的主要目的是显示一个进度条,该进度条在后台告诉进程的进度(我尚未实现代码),一旦进程完成,请刷新页面并做出响应。

谢谢

1 个答案:

答案 0 :(得分:0)

如果要检查过程的进度,则可能需要轮询机制 作为解决方案。
这要求您拥有一个模型,该模型具有确定您的扫描状态的状态 仍在进行中或已经成功。

由于您将重新加载页面以显示结果,因此应该 index视图中的逻辑可返回不同的模板或上下文 用户何时尚未开始扫描以及扫描何时成功。

from django.http import JsonResponse

def index(request):

    if status == 'success':
        # `status` may come from a Model which has a state .
        # If `status` is 'success' this means that your scanning has 
        # finished so you can have a different page or update context_list
        # based on success data.

    # Display input form
    form = scannerForm()

    return render(request, 'form.html', {
        'form': form,
        'context_list' : context_list,
        'scanSummary' : scanSummary
    })

您需要一个视图来连续检查扫描状态并返回JSON响应。

def scanner(request):
    #All Background process code goes here

    form = scannerForm(request.POST)
    status = form.perform_task()
    # During the task, your Model state should also be 
    # updated and return the status whether it is success, pending or failed etc..

    return JsonResponse({
        'status': status,
    })

运行ajax轮询以检查scanner视图。

<script type="text/javascript">

$(document).on('submit','#scanForm', function(e){
  e.preventDefault();
  checkScanStatus();
});

function checkScanStatus () {
  $.ajax({
    type: 'POST',
    url: '/scanner/',
    data: {
      email: $('#email').val(),
      context: $('#context').val(),
      csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
    },
    success: handleCheckScanStatus,
    error: handleScanError
  });
}


function handleCheckScanStatus (result) {
    if (result.status == 'success') {
      // Reload the page and display the condition you set for 'success' state
      // on the `index` view.
      location.reload();
    } else {
      // Show progress bar indicating that the process running in the background
      const interval = 5000; // Five seconds
      window.setTimeout(checkScanStatus, interval);
    }
}


function handleScanError (response) {
  console.error(response)
}
</script>

我建议调查django celery用于异步任务,django-fsm用于转换模型状态。

如果您只需要一个简单的加载器而无需检查后台任务的特定状态,则可以使用jQuery AJAX的beforeSend方法显示进度条,直到AJAX请求完成。

相关问题