Django应用程序未与JavaScript代码块进行通信

时间:2019-06-27 20:38:05

标签: javascript python django django-views

我有一个Django应用程序,该应用程序接受表单中的 Elasticsearch查询,并生成可下载的报告。较早的迭代效果很好,但是我们决定添加一个组件,该组件每十秒钟检查一次是否创建了报告。我们的最终目标是让它反复检查是否已完成报告(如果未完成,则告诉用户报告仍在处理中),然后添加按钮以下载报告,或者只是使其自动开始下载。

但是,我的应用程序似乎没有调用 form.html 中的 javascript 块。运行此命令时,它会显示{"file_created": False},直到我手动刷新自己,然后切换为True。我尝试在check_progress中注释掉的代码(这基本上是我在 form.html 中的代码所做的...),但是返回了错误。

如何使他们交流?我想念什么?

views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
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"]
            t = threading.Thread(target=generate_doc, args=(query,))
            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, 'audit_tool/form.html', {'form': form})


@login_required
def check_progress(request):
    """
    Returns whether document generation is complete or in progress
    """
    # check if file exists, return response as a JSON
    # how to integrate with js code in html to continuously check and refresh
    # only shows true when refreshed; how to talk to html??
    file = "/report.docx"
    data = {
        "file_created": os.path.exists(file)
    }
    # if os.path.exists(file):
        # response = generate_doc(query)
        # return response
    # else:
        # return HttpResponseRedirect('/check_progress/')
        # this does not work, "10.168.83.100 redirected you too many times.
        # Try clearing your cookies.
        # ERR_TOO_MANY_REDIRECTS"
    return JsonResponse(data)


@login_required
def return_doc(request):
    """
    Returns file response upon user request, or error message if something goes wrong
    """
    response = generate_doc(query)
    return response

form.html

<!-- templates/django_audit/form.html -->
{% extends 'base_login.html' %}

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

    function isFileComplete() {

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

{% block title %}Form{% endblock %}
{% block content %}
<p><br></p>
<p><br></p>
<div class="alert alert-primary" role="alert">
  <b>Instruction:</b>
  {% load crispy_forms_tags %}
  <!-- form action="/report/" method="post" onsubmit="this.submit(); this.reset(); return false; -->
  <form action="/report/" method="post" onsubmit="this.submit(); this.reset(); return false;">
      {% csrf_token %}
      {{ form|crispy }}
      <input type="submit" value="Submit">
  </form>
</div>
{% endblock %}

core / urls.py

from django.contrib import admin
from django.urls import include, path
from django.views.generic.base import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from audit_tool import views

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('', TemplateView.as_view(template_name='home.html'), name='home'),
]  + static(settings.STATIC_URL, document_root=settings.STAT)

audit_tool / urls.py

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

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

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>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的密钥是GatewayProperties,而不是data.file_created行中的data.exists。而if (data.exists) {的发送,则在javascript中消除了-您不需要查询视图中的任何内容,例如文件名,因此您无需填写data: {'file_created': 'True'}

还有以下内容:

data

这意味着file = "/report.docx" data = { "file_created": os.path.exists(file) } 将保存在文件系统的根目录中,这不会发生。使用类似

report.docx

此外,您可以提供from django.conf import settings os.path.join(settings.BASE_DIR, "../upload/", "report.docx") 放置base_login.html的部分。