Django多文件上传不会将文件发送到目录

时间:2018-11-16 15:16:56

标签: django python-3.x django-uploads

我想在网站中实现多文件上传功能。该网站上已经具有上传功能,但仅适用于单个文件。我正在随意跟踪Simple Is Better Than Complex: Django Multiple Files Upload Using Ajax

我的代码:

视图-> mulit_upload.py

class BasicUploadView(View):
    def get(self, request):
        files_list = Multi_File.objects.all()

        #files_list = ['testing_123']

        print ("files_list: {0}".format(files_list))
        return render(self.request, 'myproject/multi_upload.html', {'filesList': files_list})

    def post(self, request):
        form = FileForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            multiFile = form.save()
            data = {'is_valid': True, 'name': multiFile.file.name, 'url': multiFile.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)

models.py

class Multi_File(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.FileField(upload_to='files/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

forms.py

class FileForm(forms.ModelForm):
    class Meta:
        model = Multi_File
        fields = ('file', )

multi_upload.html

{% load static %}

{% block javascript %}
  <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/vendor/jquery.ui.widget.js' %}"></script>
  <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/jquery.iframe-transport.js' %}"></script>
  <script src="{% static 'myproject/js/jQuery-File-Upload-9.14.1/js/jquery.fileupload.js' %}"></script>

  <script src="{% static 'myproject/upload-files.js' %}"></script>
{% endblock %}

{# 1. BUTTON TO TRIGGER THE ACTION #}
<div class="col-md-4">
<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" name="myfile" multiple>
  <button type="submit">Upload<span class="glyphicon glyphicon-cloud-upload"></span> </button>
</form>
</div>

{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="myfile" multiple
       style="display: none;"
       data-url="{% url 'myproject:multi_import' %}"
       data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
  <thead>
    <tr>
      <th>Uploaded Files:</th>
    </tr>
  </thead>
  <tbody>
    {% for aFile in filesList %}
      <tr>
        <td><a href="{{ aFile.file.url }}">{{ aFile.file.name }}</a></td>
      </tr>
    {% endfor %}
  </tbody>
</table>

upload_files.js

$(function () {
  /* 1. OPEN THE FILE EXPLORER WINDOW */
  $(".js-upload-files").click(function () {
    $("#fileupload").click();
  });

  /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */
  $("#fileupload").fileupload({
    dataType: 'json',
    done: function (e, data) {  /* 3. PROCESS THE RESPONSE FROM THE SERVER */
      if (data.result.is_valid) {
        $("#gallery tbody").prepend(
          "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
        )
      }
    }
  });

});

到目前为止的问题: 1.单击按钮时,上传不起作用。随即出现该框,我可以选择许多文件并“上传”到页面,即说已选择2个文件。但是然后单击“上传”会出现错误:

{"is_valid": false}

这来自视图(mulit_uploade.py),但是我有点困惑为什么

  1. 我想使用也用于单一上传功能的base.html。因此,当我将{% extends "myproject/base.html" %}添加到multi_upload.html时,出现了一个新问题,当我仅使用单一上传功能时并没有出现:

    未找到与“ myproject_about”相反的内容。 “ myproject_about”不是有效的视图函数或模式名称:

    了解更多信息»

    / myproject / import /

    中的NoReverseMatch

    未找到与“ myproject_about”相反的内容。 “ myproject_about”不是有效的视图函数或模式名称

1 个答案:

答案 0 :(得分:0)

首先,您需要一个表单集(https://docs.djangoproject.com/en/2.1/topics/forms/formsets/),以便能够一次上传多个文件。因此代码大致如下:

{% for form in formset %}
    <input type="file" name="{{form.name}}" id="{{form.id_for_label}}" />
    {{form.file.errors}}
{% endfor %}

现在,每个文件将具有一些唯一的ID,如使用formset时所看到的。 要填充表中的数据,您需要侦听文件更改事件并更改表。

<td data-name="fileUniqueId1"></td>
<td data-name="fileUniqueId2"></td>
<td data-name="fileUniqueId3"></td>

$("form input[type='file']").change(function(e){
    var fileId = e.target.id;
    $("table td[data-name='"+ fileId +"']").text(e.target.files[0].name);
});