在Django表单中包含Dropzone表单时无法完成POST

时间:2016-07-17 20:29:25

标签: javascript django forms post dropzone.js

这绝对是我史上最前5名杀人问题! 我在Django中有一个ModelForm工作正常。问题是我想在这个表单中添加一个额外的字段 - 用于图像上传的小Dropzone.js区域。使用给定的代码示例,dropzone预览DIV已正确嵌入主窗体中。为了实现这一点,我当然以编程方式初始化了Dropzone。

如果我评论myDropzone.processQueue();,则提交按钮会将常规表单提交给视图,但不会使用Dropzone上传图像。但是,如果执行processQueue(),它将覆盖主表单提交操作,并且仅提交图像。其余内容当然被忽略了。

我只想在其余输入字段中提交图像,我想在我的Django表单中嵌入Dropzone,因为如果我将整个表单设为Dropzone,并在那里添加输入字段......整个表单显示为拖放区域和样式也搞砸了。

为了使它更复杂,我为图像添加了额外的数据库表,但是我的视图准备好额外处理请求中的图像并将它们处理到数据库。 接下来,我不得不以丑陋的方式手动提供Dropzone中的CSRF(使用params: {..}),因为Dropzone无法识别表单模板引擎中的CSRF(因为它显然是以不同的形式):( < / p>

以下是模板:

<h1 class="asdf-page-title">
    Add Type
</h1>
<form id="gift-form" class="dropzone-form" method="POST" enctype="multipart/form-data">
    {% csrf_token %}


    {{ g_form.title }}

    <p class="asdf-form-title">Select Type:</p>
    <div class="asdf-form-pic-select row collapse-outer-space ">
        {% for choice in g_form.asdf_type %}
            <div class="col-4">
                <label class="type-{{ choice.choice_label }}">
                    {{ choice.tag }}
                    <span>{% trans choice.choice_label %}</span>
                </label>
            </div>
        {% endfor %}
    </div>

    <p class="asdf-form-title">Price:</p>
    <div class="asdf-type row collapse-outer-space ">
        <div class="col-4">
            {{ g_form.total_price }}
        </div>
        <div class="col-8">
            {{ g_form.currency }}
        </div>
    </div>

    <p class="asdf-form-title">Description:</p>
    {{ g_form.description }}

    <div class="dropzone dropzone-previews" id="my-awesome-dropzone"></div>

    <p>
        <input id="submit-btn" type="submit" value="{{ action_btn }}"
    </p>

</form>

<link href="{% static 'admin-users/js/ckeditor/samples/css/samples.css' %}" rel="stylesheet" type="text/css"/>
<link href="{% static 'admin-users/css/dropzone.css' %}" type="text/css" rel="stylesheet"/>
<script src="{% static 'admin-users/js/dropzone.js' %}"></script>
<script src="{% static 'admin-users/js/jquery-2.2.4.min.js' %}" type="text/javascript"></script>
<script src="{% static 'admin-users/js/ckeditor/ckeditor.js' %}" type="text/javascript"></script>
<script>
    Dropzone.autoDiscover = false;
    jQuery(document).ready(function() {

            var myyDropzone = new Dropzone("div#my-awesome-dropzone", {
                    url: "#",
                    params: {'csrfmiddlewaretoken': getCookie('csrftoken')},
                    autoProcessQueue: false,
                    addRemoveLinks: true,
                    maxFilesize: 256 * 4 * 2,
                    maxFiles: 3,
                    uploadMultiple: true,
                    parallelUploads: 10,

                    init: function() {
                        var myDropzone = this,
                            addButton = document.querySelector("#submit");

                        // First change the button to actually tell Dropzone to process the queue.
                        addButton.addEventListener("click", function(e) {
                            // Make sure that the form isn't actually being sent.
                            e.preventDefault();
                            e.stopPropagation();
                            myDropzone.processQueue();
                        });

                        // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
                        // of the sending event because uploadMultiple is set to true.
                        this.on("sendingmultiple", function() {
                            // Gets triggered when the form is actually being sent.
                            // Hide the success button or the complete form.
                        });
                        this.on("successmultiple", function(files, response) {
                            // Gets triggered when the files have successfully been sent.
                            // Redirect user or notify of success.
                        });
                        this.on("errormultiple", function(files, response) {
                            // Gets triggered when there was an error sending the files.
                            // Maybe show form again, and notify user of error
                        });
                    },
                    sending: function (file, xhr, formData) {
                        // Along with the file, shall I append all fields from the form above in the formData?
                    }
            });
    });
    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;
    }
</script>

1 个答案:

答案 0 :(得分:1)

我们通过向服务器发出两个请求来解决这个问题:常规Django表单的一个帖子及其所有数据和一个用于上传图像的Dropzone Ajax(如果有的话)。

这是通过将上传的images添加到formdata sending函数中的Dropzone来实现的。

如果有上传的图片,系统会调用myDropzone.processQueue(),否则我们会在$(".dropzone-form").submit()的JavaScript中手动提交表单。

如果myDropzone.processQueue()被执行,那么我们会在Dropzone事件successmultiple之后进入$(".dropzone-form").submit()并在一秒后执行successmultiple。为什么我们这样做?好吧,Dropzone会等到所有图片上传完毕,然后它会立即触发Dropzone.autoDiscover = false; if ($("#my-awesome-dropzone").length > 0){ var myyDropzone = new Dropzone("#my-awesome-dropzone", { url: "some_url", autoProcessQueue: false, method: "post", addRemoveLinks: true, maxFilesize: 256 * 4 * 10, maxFiles: 3, uploadMultiple: true, parallelUploads: 10, init: function () { var myDropzone = this; var addButton = $("#submit-btn"); // First change the button to actually tell Dropzone to process the queue. addButton.addEventListener("click", function (e) { // Make sure that the form isn't actually being sent. e.preventDefault(); e.stopPropagation(); if (myDropzone.getQueuedFiles().length > 0) { myDropzone.processQueue(); } else { $(".dropzone-form").submit(); } }); this.on("successmultiple", function (files, response) { setTimeout(function () { $(".dropzone-form").submit(); }, 1000); }); }, sending: function (file, xhr, formData) { formData.append('csrfmiddlewaretoken', getCookie('csrftoken')); formData.append("image", file.name); } }); } 。如果我们直接在那里提交表单,用户将会错过Dropzone的精彩动画,它会显示所有上传图像的绿色标记。动画持续大约一秒钟,因此延迟。现在我还没有发现一个更好的方法来做到这一点,而不是设置超时一秒。

以下是代码:

this.setState({mounted:true})