Javascript不呈现条件语句-Django项目

Javascript不呈现条件语句-Django项目,javascript,html,django,jquery-file-upload,Javascript,Html,Django,Jquery File Upload,目前,我正在构建一个基于Blueimp的jQuery文件上传的文件。在我1.)学习和2.)时处理多个bug,将其升级到Django版本3.0.8。我可以点击“添加文件”,选择我的文件,然后它会在屏幕上显示一些信息,如图所示。唯一正确呈现的项目是文件大小和open\u tv和close\u tv变量。JavaScript的其余部分与代码一字不差。我无法确定此问题的解决方案 Output ${name} 11.66 KB Error: {{if error === 'maxFileS

目前,我正在构建一个基于Blueimp的jQuery文件上传的文件。在我1.)学习和2.)时处理多个bug,将其升级到Django版本3.0.8。我可以点击“添加文件”,选择我的文件,然后它会在屏幕上显示一些信息,如图所示。唯一正确呈现的项目是文件大小和
open\u tv
close\u tv
变量。JavaScript的其余部分与代码一字不差。我无法确定此问题的解决方案

Output

    ${name} 11.66 KB    Error: {{if error === 'maxFileSize'}}File is too big {{else error === 'minFileSize'}}File is too small {{else error === 'acceptFileTypes'}}Filetype is not allowed {{else error === 'maxNumberOfFiles'}}Max number of files exceeded {{else}}${error} {{/if}}

views.py
从django.shortcuts导入渲染,重定向
从.models导入请求附件,ServiceRequest
从django.http导入JsonResponse、HttpResponse、HttpResponseBadRequest
从django.conf导入设置
导入操作系统
def esr_提交(请求):
#用于生成随机唯一id
导入uuid
#文件上载的设置
#您可以在此处定义其他参数,并在代码后期检查有效性
选项={
#最大文件大小(必须以字节为单位)
“最大文件大小”:10*2**20,#10 mb
#最小文件大小(必须以字节为单位)
“最小文件大小”:1*2**10,#1KB
#允许上载的文件类型
#必须为mimetype(现在为内容类型)
“acceptedformats”:(
“图像/jpeg”,
“图像/png”,
“图像/gif”,
“应用程序/pdf”,
“应用程序/vnd.ms excel”,
“application/vnd.openxmlformats of icedocument.spreadsheetml.sheet”,
“应用程序/msword”,
“application/vnd.openxmlformats of icedocument.wordprocessingml.document”,
)
}
#后请求
#表示用户已触发上载操作
如果request.method==“POST”:
#找出文件将上载到的路径
#BASE_DIR来自设置文件
temp\u path=os.path.join(settings.BASE\u DIR,“tmp”)
#如果未指定“f”查询参数,则正在上载文件
如果没有(request.GET.keys()中的“f”):#上传文件
#确保已上载一些文件
如果不是请求文件:
返回HttpResponseBadRequest('必须上载文件')
#确保指定了唯一id-非常重要
#这是必要的,因为:
#我们希望用户上传到一个唯一的目录
#但是,上传者会向服务器发出独立的请求来上传每个文件,
#因此,必须有一种方法将所有这些文件识别为一批文件
#每个会话的唯一id将完成此任务
如果不是请求。POST.get(“uid”):
返回HttpResponseBadRequest(“未指定UID”)
uid=request.POST.get(“uid”)
打印(uid)
#通过在上载文件夹中创建一个子文件夹并使用uid名称来更新临时路径
temp_path=os.path.join(temp_path,uid)
#获取上传的文件
file=request.FILES.get['FILES[]']
#初始化错误
#如果发生错误,将显示字符串错误消息
#因此,上传程序可以显示相应的消息
错误=错误
#对照选项检查错误
#文件大小
如果file.size>options[“maxfilesize”]:
error=“maxFileSize”
如果file.sizeviews.py

from django.shortcuts import render, redirect
from .models import RequestAttachment, ServiceRequest
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest
from django.conf import settings
import os

def esr_submit(request):
    # used to generate random unique id
    import uuid

    # settings for the file upload
    # you can define other parameters here and check validity late in the code
    options = {
        # maximum file size (must be in bytes)
        "maxfilesize": 10 * 2 ** 20,  # 10 mb
        # minimum file size (must be in bytes)
        "minfilesize": 1 * 2 ** 10,  # 1 kb
        # the file types which are going to be allowed for upload
        # must be in mimetype (now content type)
        "acceptedformats": (
            "image/jpeg",
            "image/png",
            "image/gif",
            "application/pdf",
            "application/vnd.ms-excel",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        )
    }

    # POST request
    # meaning user has triggered an upload action
    if request.method == 'POST':

        # figure out the path where the files will be uploaded to
        # BASE_DIR is from the settings file
        temp_path = os.path.join(settings.BASE_DIR, "tmp")

        # if 'f' query parameter is not specified, then a file is being uploaded
        if not ("f" in request.GET.keys()):  # upload file

            # make sure some files have been uploaded
            if not request.FILES:
                return HttpResponseBadRequest('Must upload a file.')

            # make sure unique id is specified - VERY IMPORTANT
            # this is necessary because of the following:
            #       We want users to upload to a unique directory
            #       however, the uploader will make independent requests to the server to upload each file,
            #       so, there has to be a method for all these files to be recognized as a single batch of files
            #       A unique id for each session will do the job

            if not request.POST.get("uid"):
                return HttpResponseBadRequest("UID not specified.")
            uid = request.POST.get("uid")
            print(uid)
            # update the temporary path by creating a sub-folder within the upload folder with the uid name
            temp_path = os.path.join(temp_path, uid)

            # get the uploaded file
            file = request.FILES.get['files[]']

            # initialize the error
            # If error occurs, this will have the string error message
            # so the uploader can display the appropriate message
            error = False

            # check against options for errors

            # file size
            if file.size > options["maxfilesize"]:
                error = "maxFileSize"
            if file.size < options["minfilesize"]:
                error = "minFileSize"
            # allowed file type
            if file.content_type not in options["acceptedformats"]:
                error = "acceptFileTypes"

            # the response data which will be returned to the uploader as json
            response_data = {
                "name": file.name,
                "size": file.size,
                "type": file.content_type
            }

            # if there was an error, add error message to response_data and return
            if error:
                # append error message
                response_data["error"] = error
                # generate json
                response_data = JsonResponse([response_data])
                # return response to uploaded with error so it can display the error message
                return HttpResponse(response_data, content_type='application/json')

            # make temporary dir if none exists already
            if not os.path.exists(temp_path):
                os.makedirs(temp_path)

            # get the absolute path of where the uploaded file will be saved
            # add some random data to the filename in order to avoid conflicts
            # when two files with same name are uploaded
            filename = os.path.join(temp_path, '(' + str(uuid.uuid4()) + ')' + ' ' + file.name)
            # open the file handler with write binary code
            destination = open(filename, "wb+")
            # save file data into the disk
            # use the chunk method in case the file is too big in order to not clutter system memory
            for chunk in file.chunks():
                destination.write(chunk)
                # close the file
            destination.close()

            # here you can add the file to a database, move it around, do anything
            # if you do move the file around, make sure to update the delete_url which will be
            # sent to the server or not include that information at all in the response.
            # // This will be where the file will be moved from temp to the database upon submittal of the esr form
            # or when the esr is saved as draft //

            # allows to generate properly formatted and escaped url queries

            import urllib.parse
            # url for deleting the file in case the user decides to delete it
            response_data["delete_url"] = request.path + "?" + urllib.parse.urlencode(
                {"f": uid + "/" + os.path.split(filename)[1]}
            )
            # specify the delete type - must be POST for csrf
            response_data["delete_type"] = "POST"

            # generate the json data
            response_data = JsonResponse([response_data], safe=False)
            # response type
            response_type = "application/json"

            # QUIRK HERE
            # in jQuery uploader, when it falls back to uploading using iFrames,
            # the response content type has to be text/html
            # if json wil be sent, error will occur
            # if iFrames is sending the request, it's headers are a little different compared
            # to the jQuery AJAX request
            # They have different sets of HTT_ACCEPT values
            # so if the text/html is present, the file was uploaded using iFrame because
            # that value is not in the set when uploaded by XHR
            if "text/html" in request.META["HTTP_ACCEPT"]:
                response_type = "text/html"

            # return the data to the uploading plugin
            print(response_data)
            print(response_type)
            return HttpResponse(response_data, content_type=response_type)

        else:  # file has to be deleted from the temp dir

            # get the file path by getting it from the query (e.g. '?f=filename.here')
            filepath = os.path.join(temp_path, request.GET["f"])

            # make sure the file exists
            # if not return error
            if not os.path.isfile(filepath):
                return HttpResponseBadRequest("File does not exist")

            # delete the file
            # this step might not be a secure method so extra security precautions might have to be taken
            os.remove(filepath)

            # generate true json result
            # in this case is it a json True value
            # if true is not returned, the file will not be removed form the upload queue
            response_data = JsonResponse(True)

            # return the result data here
            # it always has to be json
            return HttpResponse(response_data, content_type="application/json")

    else:  # it is a GET method
        context = {
            # the unique id which will be used to get the folder path
            "uid": uuid.uuid4(),
            # these two are necessary to generate the jQuery templates
            # they have to be included here since they conflict with django template system
            "open_tv": '{{',
            "close_tv": '}}',
            # some of the parameters to be checked by javascript
            "maxfilesize": options["maxfilesize"],
            "minfilesize": options["minfilesize"],
        }
        return render(request, "esr_submit/esr_submit_jquery.html", context)
base.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
{% load static %}


<head>
    <meta charset="UTF-8">
    <title>EG Services - {% block title %}{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!--CDNs
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> -->
<!--    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">-->
    <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}">
    <script src="https://kit.fontawesome.com/5a54e295bd.js" crossorigin="anonymous"></script>
    <script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
    <link rel="icon" href="{% static 'base/icons/favicon.ico' %}">
    <!-- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->

    <!--LOCAL BOOSTRAP, JQUERY AND POPPER AS BACKUP TO CDN-->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'js/jqueryUI/jquery-ui.css' %}">
    <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
    <link rel="stylesheet" href="{% static 'css/jquery.fileupload.css' %}"/>
    <link rel="stylesheet" href="{% static 'css/jquery.fileupload-ui.css' %}"/>
 <!-- CSS adjustments for browsers with JavaScript disabled -->
    <noscript
      ><link rel="stylesheet" href="{% static 'css/jquery.fileupload-noscript.css' %}"/>
    </noscript>
    <noscript>
        <link rel="stylesheet" href="{% static 'css/jquery.fileupload-ui-noscript.css' %}"/>
    </noscript>

</head>

<body>
...
   <script src="{% static 'js/jquery.min.js' %}"></script>
    <script src="{% static 'js/popper.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
    <script src="{% static 'css/fontawesome.min.css' %}"></script>
    <script defer src="{% static 'js/all.js' %}"></script>
    <script src="{% static 'js/moment.min.js' %}"></script>

    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="{% static 'js/jqueryUI/jquery-ui.js' %}"></script>


    <!-- The Templates plugin is included to render the upload/download listings -->
    <script src="{% static 'js/tmpl.js' %}"></script>
    <!-- The Load Image plugin is included for the preview images and image resizing functionality -->
    <script src="{% static 'js/load-image.all.min.js' %}"></script>
    <!-- The Canvas to Blob plugin is included for image resizing functionality -->
    <script src="{% static 'js/canvas-to-blob.min.js' %}"></script>
    <!-- blueimp Gallery script -->
    <script src="{% static 'js/blueimp-gallery.min.js' %}"></script>
    <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
    <script src="{% static 'js/jquery.iframe-transport.js' %}"></script>
    <!-- The basic File Upload plugin -->
    <script src="{% static 'js/jquery.fileupload.js' %}"></script>
    <!-- The File Upload processing plugin -->
    <script src="{% static 'js/jquery.fileupload-process.js' %}"></script>
    <!-- The File Upload image preview & resize plugin -->
    <script src="{% static 'js/jquery.fileupload-image.js' %}"></script>
    <!-- The File Upload audio preview plugin -->
    <script src="{% static 'js/jquery.fileupload-audio.js' %}"></script>
    <!-- The File Upload video preview plugin -->
    <script src="{% static 'js/jquery.fileupload-video.js' %}"></script>
    <!-- The File Upload validation plugin -->
    <script src="{% static 'js/jquery.fileupload-validate.js' %}"></script>
    <!-- The File Upload user interface plugin -->
    <script src="{% static 'js/jquery.fileupload-ui.js' %}"></script>
    <!-- The main application script -->
    <script src="{% static 'js/demo.js' %}"></script>
    <!-- The XDomainRequest Transport is included for cross-domain file deletion for IE 8 and IE 9 -->
    <!--[if (gte IE 8)&(lt IE 10)]
      <script src="{% static 'js/cors/jquery.xdr-transport.js' %}"></script>
    <![endif]-->

    <script src="{% static 'js/jquery.ui.widget.js' %}"></script>
    <script src="{% static 'js/jquery.iframe-transport.js' %}"></script>
<!--    <script src="{% static 'js/jquery.fileupload.js' %}"></script>-->
    <script src="{% static 'js/script.js' %}"></script>
    <script src="{% static 'js/datatables.min.js' %}"></script>
    <script>
    $( function() {
        $( "#id_due_date" ).datepicker();
        $( "#anim" ).on( "change", function() {
            $( "#id_due_date" ).datepicker( "option", "showAnim", $( this ).val() );
        });
    });
    </script>

</body>

esr_submit_jquery.html

{% extends "main/base.html" %}
{% block title %}
Submit an ESR
{% endblock %}
{% load crispy_forms_tags %}

<script type="text/javascript">
$(function() {
    'use strict';

    // Initialize the jQuery File Upload Widget
    // reference https://github.com/blueimp/jQuery-File-Upload
    $('#fileupload').fileupload({
        // this formData is necessary to pass the csrf and pass uid to django
        formData: [
            { name: "uid", value: "{{ uid }}"},
//            { name: "csrfmiddlewaretoken", value: "{{ csrf_token }}"}
        ],
        maxFileSize: {{ maxfilesize }},
        minFileSize: {{ minfilesize }},
        sequentialUploads: true
    });

    // Load existing files
    $.getJSON($('#fileupload form').prop('action'), function (files) {
        var fu = $('#fileupload').data('fileupload');
        fu.adjustMaxNumberOfFiles(-files.length);
        fu.renderDownload(files)
                .appendTo($('#fileupload .files'))
                .fadeIn(function () {
                    // Fix for IE7 and lower:
                    $(this).show();
                });
    });

    // Open the download dialogs via iframes, to prevent aborting current uploads
    $('#fileupload .files a:not([target^_blank])').on('click', function (e) {
        e.preventDefault();
        $('<iframe style="display:none;"></iframe>')
                .prop('src', this.href)
                .appendTo('body');
    });
});
</script>

{% block content %}
<div>
    <input type="text">
</div>
<div id="fileupload">
    <form action="{% url 'esr_submit:esr_submit' %}" method="post" enctype="multipart/form-data" >
        {% csrf_token %}
        <div class="fileupload-buttonbar">
            <span class="btn btn-success fileinput-button">
                <i class="fas fa-plus"></i>
                <span>Add files...</span>
                <input type="file" name="files[]" multiple>
            </span>
            <button type="submit" class="btn btn-primary start"><i class="fas fa-upload"></i>
                <span>Start upload</span>
            </button>
            <button type="reset" class="btn btn-warning cancel"><i class="fas fa-ban"></i>
                <span>Cancel upload</span>
            </button>
            <button type="button" class="btn btn-danger delete"><i class="fas fa-trash-alt"></i>
                <span>Delete files</span>
            </button>
        </div>
    </form>
    <div class="fileupload-content">
        <table class="files"></table>
        <div class="fileupload-progressbar"></div>
    </div>
</div>

<script id="template-upload" type="text/x-jquery-tmpl">
    <tr class="template-upload{{ open_tv }} if error{{ close_tv }} ui-state-error{{ open_tv }}/if{{ close_tv }}">
        <td class="preview"></td>
        <td class="name">${name}</td>
        <td class="size">${sizef}</td>
        {{ open_tv }}if error{{ close_tv }}
        <td class="error" colspan="2">Error:
            {{ open_tv }}if error === 'maxFileSize'{{ close_tv }}File is too big
            {{ open_tv }}else error === 'minFileSize'{{ close_tv }}File is too small
            {{ open_tv }}else error === 'acceptFileTypes'{{ close_tv }}Filetype is not allowed
            {{ open_tv }}else error === 'maxNumberOfFiles'{{ close_tv }}Max number of files exceeded
            {{ open_tv }}else{{ close_tv }}${error}
            {{ open_tv }}/if{{ close_tv }}
        </td>
        {{ open_tv }}else{{ close_tv }}
        <td class="progress">
            <div></div>
        </td>
        <td class="start">
            <button>Start</button>
        </td>
        {{ open_tv }}/if{{ close_tv }}
        <td class="cancel">
            <button>Cancel</button>
        </td>
    </tr>
</script>
<script id="template-download" type="text/x-jquery-tmpl">
    <tr class="template-download{{ open_tv }} if error{{ close_tv }} ui-state-error{{ open_tv }}/if{{ close_tv }}">
        {{ open_tv }}if error{{ close_tv }}
        <td></td>
        <td class="name">${name}</td>
        <td class="size">${sizef}</td>
        <td class="error" colspan="2">
            {{ open_tv }}if error === 1{{ close_tv }}File exceeds upload_max_filesize (php.ini directive)
            {{ open_tv }}else error === 2{{ close_tv }}File exceeds MAX_FILE_SIZE (HTML form directive
            {{ open_tv }}else error === 3{{ close_tv }}File was only partially uploaded
            {{ open_tv }}else error === 4{{ close_tv }}No file was uploaded
            {{ open_tv }}else error === 5{{ close_tv }}Missing a temporary folder
            {{ open_tv }}else error === 6{{ close_tv }}Failed to write file to disk
            {{ open_tv }}else error === 7{{ close_tv }}File upload stopped by extension
            {{ open_tv }}else error === 'maxFileSize'{{ close_tv }}File is too big
            {{ open_tv }}else error === 'minFileSize'{{ close_tv }}File is too small
            {{ open_tv }}else error === 'acceptFileTypes'{{ close_tv }}Filetype not allowed
            {{ open_tv }}else error === 'maxNumberOfFiles'{{ close_tv }}Max number of files exceeded
            {{ open_tv }}else error === 'uploadedBytes'{{ close_tv }}Uploaded bytes exceed file size
            {{ open_tv }}else error === 'emptyResult'{{ close_tv }}Empty file upload result
            {{ open_tv }}else{{ close_tv }}${error}
            {{ open_tv }}/if{{ close_tv }}
        </td>
        {{ open_tv }}else{{ close_tv }}
        <td class="preview">
            {{ open_tv }}if thumbnail_url{{ close_tv }}
            <a href="${url}" target="_blank"><img src="${thumbnail_url}"></a>
            {{ open_tv }}/if{{ close_tv }}
        </td>
        <td class="name">
            <a href="${url}" {{ open_tv }}if thumbnail_url{{ close_tv }}
               target="_blank"{{ open_tv }}/if{{ close_tv}}>${name}</a>
        </td>
        <td class="size">${sizef}</td>
        <td colspan="2"></td>
        {{ open_tv }}/if{{ close_tv }}
        <td class="delete">
            <button data-type="${delete_type}" data-url="${delete_url}">Delete</button>
        </td>
    </tr>
</script>
{% endblock content%}


script.js

/* Enable Django CSRF-ready AJAX calls - directly from the Django docs. Put this code before any jQuery that uses AJAX
 as a catch-all for cross site forgery protection (CSRF)*/

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$(function() {
    'use strict';

    // Initialize the jQuery File Upload Widget
    // reference https://github.com/blueimp/jQuery-File-Upload
    $('#fileupload').fileupload({
        // this formData is necessary to pass the csrf and pass uid to django
        formData: [
            { name: "uid", value: "{{ uid }}"},
//            { name: "csrfmiddlewaretoken", value: "{{ csrf_token }}"}
        ],
        maxFileSize: "{{ maxfilesize }}",
        minFileSize: "{{ minfilesize }}",
        sequentialUploads: true
    });

    // Load existing files
    $.getJSON($('#fileupload form').prop('action'), function (files) {
        var fu = $('#fileupload').data('fileupload');
        fu.adjustMaxNumberOfFiles(-files.length);
        fu.renderDownload(files)
                .appendTo($('#fileupload .files'))
                .fadeIn(function () {
                    // Fix for IE7 and lower:
                    $(this).show();
                });
    });

    // Open the download dialogs via iframes, to prevent aborting current uploads
    $('#fileupload .files a:not([target^_blank])').on('click', function (e) {
        e.preventDefault();
        $('<iframe style="display:none;"></iframe>')
                .prop('src', this.href)
                .appendTo('body');
    });
});