【问题标题】:Django image upload using dropzone使用 dropzone 上传 Django 图像
【发布时间】:2014-05-05 18:28:36
【问题描述】:

我遇到这个问题已经有一段时间了,我找不到解决方案,我正在尝试使用 dropzone.js 上传图片和我的form.is_valid() 失败。传递错误:This field is required. 你能帮我弄清楚我做错了什么吗?

models.py:

class Image(models.Model):
    item_id = models.ForeignKey(Item,blank=True,null=True)
    image = models.ImageField(upload_to='item_images/%Y/%m/%d')
    def __unicode__(self):
        return smart_unicode(self.image)

forms.py:

class ImageForm(forms.ModelForm):

    class Meta:
        model = Image
        exclude = ['item_id']

views.py:

def upload_image(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            result = 'success'
        return render(request, 'page.html', {'form':form})

page.html:

        <form class="dropzone" id="myDropzone" action="/upload_image/" method="post" enctype="multipart/form-data">
            {% csrf_token %}
        </form>

【问题讨论】:

    标签: django django-forms dropzone.js


    【解决方案1】:

    表单需要类型为“文件”和名称为“图像”的输入。

    【讨论】:

      【解决方案2】:

      我不知道我现在展示的内容是否会对您有所帮助,但您可以在不使用表格的情况下这样做,也许它会帮助这里的其他人。 使用 dropzone 让我做了一个解决方法,因为 ajax、文件和 django 结合起来总是有点复杂。

      所以在我的 html 中我有这个代码:

      <div class="logos">
        <i class="fa fa-upload" id="dropzone_icon" data-name="icon" title="{% trans "Drag and drop or click" %}" alt="{% trans "Drag and drop or click" %}" ></i>
        <input type="hidden" name="icon" value="" >
        <input type="hidden" name="icon_name" value="" >
        <div class="img-holder">
          <img title='{% trans "Upload a Company Icon" %}' id="img_icon" alt='{% trans "Company icon" %}' src="{* icon *}"/>
        </div>
        <label>{% trans "Company Icon" %}</label>
      </div>
      

      在我的 js 中我得到了这个:

      dropz = new Dropzone(value, {
          url: "branding/dropzone",
          maxFiles: 1,
          acceptedFiles: "image/*",
          thumbnail: function(file, dataUrl) {
              /* change existing image */
              var file_type = file.name.split('.');
              file_type = file_type[file_type.length - 1];
              if(!(file_type=="png" || file_type=="jpg" || file_type=="jpeg")){
                  createAlert('file type must be .png, .jpg or .jpeg', '#pp_content', 'alert');
                  return false;
              }
              $("input[name='icon']").val(dataUrl.split(",")[1]);
              $("input[name='icon_name']").val(file.name);
              $("#img_" + type).prop("src", dataUrl);
              this.removeFile(file);
          },
          previewTemplate: "<span></span>",
          autoProcessQueue: false
      });
      

      这告诉 dropzone 将值插入到输入中(图像的 base64 表示和文件名),所以基本上我将图像作为字符串发送。

      在 ajax 中将输入作为表单发送后,这就是我在 views.py 中处理它们的方式:

      import datetime
      from django.core.files.base import ContentFile
      
      def base64_to_image(img_b64,img_name):
      """
      Creates image file from bas64 encoded data
      :param img_b64: base64 data
      :param img_name: filename for created image
      :return: file or false if there's no data
      """
      if img_b64:
          image_data = b64decode(img_b64)
          img_file = ContentFile(image_data,datetime.datetime.now().strftime("%y%d%m_%H%M%S") + img_name)
          return img_file
      else:
          return False
      
      company.icon = base64_to_image(request.POST["icon"], request.POST["icon_name"])
      company.save()
      

      这是我在使用 dropzone 方面所做的工作,也许它也会帮助这里的其他人

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-21
        • 2017-05-28
        • 1970-01-01
        • 2019-09-20
        • 2014-12-30
        • 2018-06-01
        • 1970-01-01
        • 2020-08-26
        相关资源
        最近更新 更多