将DropzoneJS与Django一起使用时的MultiValueDictKeyError

时间:2017-07-28 02:40:08

标签: javascript html django dropzone.js

我目前正在为网站制作个人资料图片功能,我开始使用DropzoneJS,但我在提交文件时遇到了问题。图片会很好地落入区域,但它会出现在" X"在它上面,当我将鼠标悬停在图片上时,我可以看到MultiValueDictKeyError错误。当我单击提交按钮而不选择文件时,我得到的错误是相同的。所以我认为问题是该文件不是由button提交的?我该怎么做?

HTML / JS:

<script type='text/javascript'>

Dropzone.options.myDropzone = {

    init : function() {
        var submitButton = document.querySelector("#submitBtn")
        myDropzone = this;
        submitButton.addEventListener("click", function() {
            myDropzone.processQueue();
        });
        this.on("addedfile", function() {
            document.getElementById('submitBtn').style.visibility = "visible";
        });

        this.on('addedfile', function(){
            if (this.files[1]!=null){
                this.removeFile(this.files[0]);
            }
        });


    }
};

Dropzone.options.myAwesomeDropzone = {
  accept: function(file, done) {
    console.log("uploaded");

  },
  init: function() {
    this.on("addedfile", function() {
      if (this.files[1]!=null){
        this.removeFile(this.files[0]);
        //document.getElementById('submitBtn').style.visibility = "visible";
      }
    });
  }


};
</script>
<!-- Modal -->
<div id="picModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close"></span>
    <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %}
        <button id='submitBtn' type='submit' style='visibility: hidden;'> Submit </button>
        <input id='submit-all' type='file' name='uploaded_image'/>
            {{form}}
    </form>
  </div>

</div>

</body>

Here's a screenshot of the error

修改

我将autoProcessQueue: false,添加到myDropzone。当我将鼠标悬停在图片上时,我没有得到这个问题。相反,现在当我按提交时,它只是带我到MultiValueDictKeyError错误页面

*编辑2 **

views.py

def profile_test(request):
    #going to use this view to display the profile page, and test alterations to it
    form = ImageUploadForm(request.POST, request.FILES)
    user = User.objects.get(id=request.user.id)
    if request.method == "POST": 
        print 'valid'
        user.userprofile.img = request.POST.get('uploaded_image', False)
        user.userprofile.save()
        return HttpResponseRedirect(reverse("profile_test"))
    else:
        print 'invalid'
        form = ImageUploadForm()

    return render(request, 'profile_test.html', {form:'form', user: 'user'})

我曾经user.userprofile.img = request.FILES["uploaded_image"]但改变了它,似乎更好地改变了事情。现在图像将落入区域,当我将鼠标悬停在区域上时,我不会看到该错误。但是现在当我提交它时,dropzone消失了,而配置文件pic也没有改变。

1 个答案:

答案 0 :(得分:2)

我希望img属性是FileField。正确?

user.userprofile.img = request.POST.get('uploaded_image', False)

请试试这个。

user.userprofile.img = request.FILES.get('uploaded_image')
# if you have multiple files to upload
user.userprofile.img = request.FILES.getlist('uploaded_image')