Django App Not Communicating with JavaScript Code Block

穿精又带淫゛_ 提交于 2019-12-11 20:14:33

问题


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.

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>

回答1:


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.

Also the following:

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

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")

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



来源:https://stackoverflow.com/questions/56798192/django-app-not-communicating-with-javascript-code-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!