AJAX GET请求被忽略

时间:2019-07-01 16:53:26

标签: python django ajax django-views

我是AJAX请求的新手,并且仍在学习Django,但是我有一个项目,用户在其中输入Elasticsearch查询,然后为用户生成可下载的文档(报告)。

我有一个AJAX请求,要不断检查我的form.html文件中是否存在某个文件,而且似乎根本没有发现该文件。我可以说这是因为它不会给我任何警报,它只是在大约30秒后自动超时处理大型请求。

我尝试在views.py中编写一个临时修复程序,该修复程序基本上是试图做form.html中的javascript所做的事情,但是A)我觉得这不是最好的使用方法在生产中,B)实质上并没有浪费时间来重新发明轮子,C)我希望用户在其端收到某种警报或指示,表明该报告正在进行中,并且然后准备下载时。

如何修改我的代码以实际执行AJAX请求?还是为什么看来AJAX请求无法正常工作?

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('form/', include('audit_tool.urls')),
    path('report/', include('audit_tool.urls')),
    path('check_progress/', views.check_progress, name='check_progress'),
    # path('return_doc/', views.return_doc, name='return_doc'),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
]  + static(settings.STATIC_URL, document_root=settings.STAT)

audit_tool / urls.py

urlpatterns = [
    path('', views.get_query, name='form'),
]  + static(settings.STATIC_URL, document_root=settings.STAT)

views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from docx import Document
import os
import threading
from .forms import QueryForm
from .models import *


@login_required
def get_query(request):
    if request.method == 'POST':
        form = QueryForm(request.POST)
        if form.is_valid():
            query = form.cleaned_data["query"]
            fn = str(time.time()).replace(".", "_") + ".docx"
            t = threading.Thread(target=generate_doc, args=(query, fn))
            t.start()
            return HttpResponseRedirect('/check_progress/')
        else:
            return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.")
    else:
        form = QueryForm()
        return render(request, 'icm_audit_tool/form_template.html', {'form': form})


@login_required
def check_progress(request):
    """
    Returns whether document generation is complete or in progress
    """
    fn = request["filename"]
    file = "/app/created_files/" + fn
    while not os.path.exists(file):
        time.sleep(10)
        if os.path.exists(file):
            doc = Document(file)
            response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
            response['Content-Disposition'] = 'attachment; filename={}'.format(fn)
            doc.save(response)
            return response

form.html

{% block javascript %}
  <script>
    var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds

    function isFileComplete() {

        $.ajax({
        url: '/check_progress/',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            if (data.file_created) {
                alert("Your file is ready to download!");
                clearInterval(checkInterval);
            } else {
                alert("Your report is still being created, please hold.");
                checkInterval;
            }
        }
    });
   }
  </script>
{% endblock %}

base_login.html

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<html lang="en">
{% load static %}
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
    <link rel="shortcut icon" href="link/to/company/iconicon.ico" type="image/vnd.microsoft.icon" />
    <title>Audit Report Tool</title>
  </head>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="#">Dept</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="../">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="../admin">Admin</a>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-8">
        <hr class="mt-0 mb-4">
        <img src="{% static "logo.png" %}" alt="Company Logo" align="left"></img>
        <img src="{% static "logo.png" %}" alt="Dept Logo" align="right" width="140" height="140"></img>
        <h1 align="center"><font size="6"> Audit Report Tool</font></h1>
      </div>
    </div>
  </div>
<body>
  <main>
    {% block content %}
    {% endblock %}
  </main>
{% block javascript %}{% endblock %}
</body>
</html>

0 个答案:

没有答案