Javascript 如何在Django中为多个图像字段使用Dropzone上载多个图像

Javascript 如何在Django中为多个图像字段使用Dropzone上载多个图像,javascript,python,django,dropzone.js,Javascript,Python,Django,Dropzone.js,我正在从事一个项目,其中的功能是用户可以上传他的多个图像与拖放功能。我正在使用Django python进行开发。我已经在django模板中实现了拖放功能,但在提交表单数据时遇到了图像错误。 我的Html模板代码是: <form id="newUserForm" name="newUserForm" data-abide action="{% url 'saveNewUserInfo'%}" method="post" enctype="multipart/form-data">

我正在从事一个项目,其中的功能是用户可以上传他的多个图像与拖放功能。我正在使用Django python进行开发。我已经在django模板中实现了拖放功能,但在提交表单数据时遇到了图像错误。
我的Html模板代码是:

<form id="newUserForm" name="newUserForm" data-abide action="{% url 'saveNewUserInfo'%}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="section"></div>
            some input fields
        <!-- The div for uploading the images -->
        <div class="dropzone" style="border: 1px solid red;"></div>
        <input type="submit" value="save">
</form>
forms.py

class CustomerInfoForm(forms.ModelForm):

    class Meta:
        model = CustomerProfile

请建议如何将dropzone多个图像存储到这些图像字段中。感谢您的建议。

我很高兴您解决了这个问题。我花了几个小时来解决这个问题我就是这样解决的:

使用dropzone的主要问题是,一旦文件被放到dropzone中,它就会开始上传。因此,图像不会与表单数据的其余部分一起上载

为了解决这个问题,我必须使用以下设置以编程方式创建dropzone对象:

$(document).ready(function(){
  var list_of_files = new Array();
  Dropzone.autoDiscover = false;  //prevent dropzone to automatically discover the dropzone object in your html
  $("div#dropzone").dropzone({
        uploadMultiple: true, // allow multiple upload
        autoProcessQueue: false, // prevent dropzone from uploading automatically
        url: "/", //dropzone needs a url attribute or it complains, what value you put here does not really matter. It is only purpose is to prevent a javascript error message from chrome console
        maxFiles: 5, //set max uploads to 5 since you only have 5 image files in your model
        init: function(){
            //everytime a file is uploaded, save the file object
            //for later use
            this.on("addedfile", function(file)
            {
                if (list_of_files.length < 5)
                {
                    list_of_files.push(file)
                    console.log("file added");
                }
            });
        }
    });

  // the following function override the "submit" button in the form
  $(document).on("click", "button", function(e){
        e.preventDefault() //prevent the form from submitting 
        console.log('num of files: ' + list_of_files.length);
        var formData = new FormData(); // construct our own upload data
        var inputs = $("#newUserForm input");

        //get all of the data from textboxes
        $.each(inputs, function(obj, v){
            var name = $(v).attr("name")
            var val = $(v).val();
            console.log('name: ' + name + ' value: ' + val);
            formData.append(name, val);
        });

        //get the file object from dropzone and put it into our formdata
        for(i=0;i<list_of_files.length;i++)
        {
            formData.append('user_image'+(i+1), list_of_files[i]);
        }

        var request = new XMLHttpRequest();
        request.open("POST", "/"); //config your post url here
        request.send(formData);  //send the post request to server
    });
});
上面的所有代码都是将每个文本框中的数据连同图像一起提交到视图中。py一步完成

以下是视图。py

def index(request):
    if request.method == 'POST':
        form = CustomerInfoForm(request.POST)

        if (form.is_valid()):
            instance = form.save(commit=False)
            #request.FILES contains all of the uploaded images
            #key is 'user_image1', 'user_image2', value is the image file in memory
            for key, value in request.FILES.iteritems():
                a_path = '/a/b'
                save_uploadfile_to_disk(a_path, file) 
                setattr(instance, key, a_path) //I made up the path here
            form.save() //save the form for real
            #do not forget to return a response
        else:
            print form.errors  #for debugging only 

    else:
        form = CustomerInfoForm()
        context = {'form': form}
        return render(request, 'test_dropzone/index.html', context)

def save_uploadfile_to_disk(full_path, file):
    with open(full_path, 'w+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
我使用Django 1.8测试了这个解决方案,它是有效的。我检查了数据库,路径已正确写入记录

现在,反思一下这个解决方案,它有点违背了使用dropzone的目的。因为用户无法在选择文件后立即上载照片


既然你也解决了这个问题。请发布您的解决方案,我期待从您的解决方案中学到一些新的东西:)

在上一篇文章覆盖提交的基础上,我想添加
选项:选中的
循环

     $('option:selected').each(function(){
        var name = $(this).parent().attr('name')
        if ($(this).val()) {
            var val = $(this).val()
            console.log('name: ' + name + ' value: ' + val);
            formData.append(name, val);
        }
        else {
            var val = ""
            console.log('name: ' + name + ' value: ' + val);
             formData.append(name, val);
        }
    });

@furins,请看这个问题你的观点是什么?py看起来怎么样?@Cheng,现在问题已经解决了,我使用了什么方法,我将很快给出答案。谢谢你的回复
class CustomerInfoForm(forms.ModelForm):

class Meta:
    model = CustomerProfile
    exclude=('user_image1','user_image2','user_image3','user_image4','user_image5')
def index(request):
    if request.method == 'POST':
        form = CustomerInfoForm(request.POST)

        if (form.is_valid()):
            instance = form.save(commit=False)
            #request.FILES contains all of the uploaded images
            #key is 'user_image1', 'user_image2', value is the image file in memory
            for key, value in request.FILES.iteritems():
                a_path = '/a/b'
                save_uploadfile_to_disk(a_path, file) 
                setattr(instance, key, a_path) //I made up the path here
            form.save() //save the form for real
            #do not forget to return a response
        else:
            print form.errors  #for debugging only 

    else:
        form = CustomerInfoForm()
        context = {'form': form}
        return render(request, 'test_dropzone/index.html', context)

def save_uploadfile_to_disk(full_path, file):
    with open(full_path, 'w+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
     $('option:selected').each(function(){
        var name = $(this).parent().attr('name')
        if ($(this).val()) {
            var val = $(this).val()
            console.log('name: ' + name + ' value: ' + val);
            formData.append(name, val);
        }
        else {
            var val = ""
            console.log('name: ' + name + ' value: ' + val);
             formData.append(name, val);
        }
    });