簡體   English   中英

如何使用Dropzone為多個圖像字段上傳Django中的多個圖像

[英]How to upload multiple images in Django using Dropzone for multiple image fields

我正在開發一個項目,其功能是用戶可以使用拖放功能上傳他的多個圖像。 我正在使用Django-python進行開發。 我已經在django模板中實現了drag-n-drop的功能,但是在提交表單數據時我收到圖像錯誤。
我的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>

我正在使用dropzone.js來實現拖放和可排序錯誤來自MultiValueDictKeyError at /saveNewUserInfo/, Exception Value: "'file'"
我的模型是:

class CustomerProfile(models.Model):
    customer_id  = models.CharField(db_column='customer_id', primary_key=True, max_length=20)  
    first_name   = models.CharField(db_column='first_name', max_length=30, blank=True, null=True) 
    last_name    = models.CharField(db_column='last_name', max_length=30,blank=True,null=True) 
    user_name    = models.CharField(db_column='user_name', max_length=50,unique=True)  
    phone_number = models.CharField(db_column='phone_number', max_length=15,blank=True,null=True)
    email_id     = models.EmailField(db_column='email_id', max_length=50,blank=True, null=True)  
    user_image1 = models.ImageField(upload_to=IMAGES_PATH, db_column='user_image1', max_length=100)  
    user_image2 = models.ImageField(upload_to=IMAGES_PATH, db_column='user_image2', max_length=100)  
    user_image3 = models.ImageField(upload_to=IMAGES_PATH, db_column='user_image3', max_length=100)  
    user_image4 = models.ImageField(upload_to=IMAGES_PATH, db_column='user_image4', max_length=100) 
    user_image5 = models.ImageField(upload_to=IMAGES_PATH, db_column='user_image5', max_length=100) 

forms.py

class CustomerInfoForm(forms.ModelForm):

    class Meta:
        model = CustomerProfile

請建議如何將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
    });
});

這是模板文件:

<form id="newUserForm" name="newUserForm" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    {% if form %}
       {% for field in form %}
            <p>{{ field.label_tag }} {{ field }}</p>
       {% endfor %}

    {% endif %}
    <!-- The div for uploading the images -->
    <div id="dropzone" class="dropzone"></div>
    <button id='save'> save </button>
</form>

我還將exclude添加到forms.py中 (因此這些字段不會顯示在我們的模板中,我們有dropzone來替換它們):

class CustomerInfoForm(forms.ModelForm):

class Meta:
    model = CustomerProfile
    exclude=('user_image1','user_image2','user_image3','user_image4','user_image5')

上面的所有代碼都是將每個文本框中的數據與圖像一起提交到views.py

這是views.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的目的。 因為用戶無法在選擇文件后立即上傳照片。

既然你也解決了這個問題。 請發布您的解決方案,我期待從您那里學到新東西:)

以前的帖子覆蓋提交的小升級,我想添加options:selected循環。

     $('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);
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM