上传多张图片时,仅保存一张图片

时间:2019-05-05 11:58:45

标签: python html django

最初,仅上传一张照片就可以了,但是我将其扩展为三张。

3张照片中的每张都是可单击的,触发onclick="_upload()",并且在保存页面时,照片应显示在它们各自的位置(imageimage_twoimage_three )。

但是保存页面后,最后选择的照片将显示在image_three插槽中。

即使我通过单击image(第一张图像)选择了一张照片,该照片也会显示并保存到image_three,而另两张图像保留为默认照片。

我显然可以进入后端并手动添加照片,然后将它们显示在客户端的正确空间中,但这没有帮助。

我想念什么吗?另一个问题提示需要将Image类作为ForeignKeyProfile,但是为什么有必要?

更新图像表格

<form method="POST" enctype="multipart/form-data">
          {% csrf_token %}

          <input type="file" name='image' accept="image/*"
           id="id_image">
            <a href="#">
              <img src="{{ user.profile.image.url }}" 
               onclick="_upload()">
            </a>

          <input type="file" name='image_two' accept="image/*" 
           id="id_image_two">
            <a href="#">
              <img src="{{ user.profile.image_two.url }}" 
               onclick="_upload()">
            </a>

          <input type="file" name='image_three' accept="image/*"
           id="id_image_three">
            <a href="#">
              <img src="{{ user.profile.image_three.url }}"
               onclick="_upload()">
            </a>
          <button type="submit" value="submit">
            Update Profile</button>
        </form>
<script>
function _upload(){
  document.getElementById('id_image').click();
}
function _upload(){
  document.getElementById('id_image_two').click();
}
function _upload(){
  document.getElementById('id_image_three').click();
}
</script>

个人资料模型

image           = models.ImageField(default='default.png', upload_to='profile_pics')
image_two       = models.ImageField(default='default.png', upload_to='profile_pics')
image_three     = models.ImageField(default='default.png', upload_to='profile_pics')


def __str__(self):
    return f'{self.user.username} Profile'

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    img = Image.open(self.image.path)

    if img.height > 300 or img.width > 300:
        output_size = (300, 300)
        img.thumbnail(output_size)
        img.save(self.image.path)

1 个答案:

答案 0 :(得分:2)

PdfiumViewer

您已经用相同的名称定义了3次相同的功能。

要解决此问题,请在函数中添加一个参数:

<script>
function _upload(){
  document.getElementById('id_image').click();
}
function _upload(){
  document.getElementById('id_image_two').click();
}
function _upload(){
  document.getElementById('id_image_three').click();
}
</script>
相关问题