Django应用程序未与JavaScript代码块进行通信 [英] Django App Not Communicating with JavaScript Code Block

查看:82
本文介绍了Django应用程序未与JavaScript代码块进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Django application that accepts an Elasticsearch query in a form and produces a downloadable report. An earlier iteration worked great, but we decided to add a component that checks every ten seconds if the report is done being created. Our ultimate goal is to have it check repeatedly for the completed report (and tell the user the report is still processing if not complete), and then either add a button to download the report or just have it automatically begin downloading.

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

However, my application doesn't seem to be calling on the javascript block I have in my form.html. When I run this, it says {"file_created": False} until I manually refresh myself, then it switches to True. I tried the code commented out in check_progress (which is basically what my code in form.html does...) but it returned an error.

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

How do I make them communicate? What am I missing?

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>


推荐答案

您的密钥是 data。如果(data.exists){行中的file_created ,而不是 data.exists 。并发送 data:{'file_created':'True'} ,在您的javascript中删除它-您不会在视图中查询任何内容,例如,例如文件名,因此您无需填写数据

Your key is data.file_created, not data.exists in if (data.exists) { line. And that sending of data: {'file_created': 'True'}, get rid of that in your javascript - you're not querying request for anything in your view, as, for example, the name of the file, so you don't need to fill that data.

也以下内容:

file = "/report.docx"
data = {
    "file_created": os.path.exists(file)
}

这表示 report.docx 将保存在文件系统的根目录中,这不会发生。使用类似

It implies that report.docx is going to be saved in the root of the filesystem, that's not going to happen. Use something like

from django.conf import settings
os.path.join(settings.BASE_DIR, "../upload/", "report.docx")

也可以提供 base_login.html 放置了 {%block javascript%} 的位置。

Also ,you may provide the part of base_login.html where that {% block javascript %} is placed.

这篇关于Django应用程序未与JavaScript代码块进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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