Django AJAX成功上的渲染模板 [英] Django render template on AJAX success

查看:96
本文介绍了Django AJAX成功上的渲染模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于Django的Web应用程序,该应用程序需要用户输入并执行密集的后台任务,该任务将在五到十分钟内完成.后台任务完成后,几乎没有参数可提供给模板进行渲染.一切正常,然后页面加载.

I am trying to make a web application based on Django that takes user input and performs Heavy background task that completes in almost five to ten minutes. When the background task is completed, few parameters are supplied to the template to render. Everything works fine and the page loads after that.

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

But when I am trying to use AJAX for this as it does'nt seems good that the page is loading for so long due to background heavy processing, I am not able to figure out how to reload the page (Though I am able to show an alert on completion but instead of this I want to re-render the page)

这是我的views.py代码:

Here is my views.py code:

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

这是我的AJAX电话

<script type="text/javascript">
$(document).on('submit','#scanForm', function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: '/scanner/',
        data: {
            email: $('#email').val(),
            context: $('#context').val(),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(response){
            alert('Scan Completed');
            location.reload();
        }
    });
});

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

I am not able to figure out, what should I write in success function to reload the page that index function has returned to template.

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

My main motive is to show a progress bar that tells the progress of process in background (I have'nt implemented the code yet )and once the process is completed , refresh the page with response.

谢谢

推荐答案

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

If you want to check the progress of a process you may need a polling mechanism as a solution.
This requires you to have a Model that has a state to determine if your scan is still in progress or has succeeded.

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

Since you will reload the page to display the results, you should have a logic in your index view to return a different template or context for when a user has yet to start scanning and when the scanning is successful.

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响应.

You need a view to continuously check the scan status and returns a JSON response.

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 视图.

Run the ajax poll to check the scanner view.

<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 用于转换模型状态.

I would suggest to look into django celery for async tasks and django-fsm for transitioning model states.

如果您只需要一个简单的加载程序,而无需检查后台任务的特定状态,则可以使用jQuery AJAX的

If you just want a simple loader and do not need the check the specific status of your background task, you can use jQuery AJAX's beforeSend method to display a progress bar until the AJAX request finishes.

这篇关于Django AJAX成功上的渲染模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆