【问题标题】:resizing an image only if upload_to was called django仅当 upload_to 被称为 django 时才调整图像大小
【发布时间】:2015-08-24 19:41:00
【问题描述】:

我有以下代码,models.py:

class Location(models.Model):
         image_file = models.ImageField(upload_to=upload_to_location, null=True, blank=True)
         name = models.CharField(max_length=200)

调用upload_to 函数,图像被重命名。然后我的保存方法

def save(self, *args, **kwargs):
        try:
            this = Location.objects.get(id=self.id)
            if this.image_file:
                os.remove(this.image_file.path)
        except ObjectDoesNotExist:
            pass
        super(Location, self).save(*args, **kwargs)
        try:
            this = Location.objects.get(id=self.id)
            if this.image_file:
                resize(this.image_file.path)
        except ObjectDoesNotExist:
            pass

def upload_to_location(instance, filename):
    blocks = filename.split('.')
    ext = blocks[-1]
    filename = "%s.%s" % (instance.name.replace(" ", "-"), ext)
    return filename

检查以前上传的文件是否存在,如果存在,则将其删除。然后在保存后,它会再次检查文件是否存在,然后调用resize 函数。如果我上传文件并单击保存,那就行了。但是,如果我只更改位置的名称,则会调用 os.remove 函数,删除我的文件,然后 resize 函数会出错。 因此,我只想在用户上传upload_to 时调用os.remove 函数。

所以我尝试了几件事,但无法完成。我还尝试了pre_savepost_save 信号。因此,我在获取图像路径时遇到了问题:

@receiver(pre_save, sender=Company)
def my_function2(sender, instance, **kwargs):
    print instance.path   #didn't work
    print os.path.realpath(instance) #didn't work

有谁知道我如何使用pre_save 或其他方法解决这个问题?

【问题讨论】:

  • 您是否阅读/考虑过实施custom upload handler 以满足您的需求?关于如何做到这一点的另一个可能的提示here
  • 你写过upload_to参数的自定义函数吗?
  • 是的,我做到了,我更新了我的问题,所以在 upload_to_location 中的名称将被更改

标签: python django save image-uploading


【解决方案1】:

如果您只想在调用upload_to 时才调用os.remove,为什么不将该代码移到upload_to_location 函数中?

def upload_to_location(self, filename):
    try:
        this = Location.objects.get(id=self.id)
        if this.image_file:
            os.remove(this.image_file.path)
    except ObjectDoesNotExist:
        pass
    # do something else...

这样,当upload_to被调用时,os.remove就会被调用。

附加内容

您可以通过调用该文件字段的delete() 方法来删​​除文件,而不是调用os.remove 来删除关联文件。

if this.image_file:
    this.image_file.delete(save=True)

save=True 在删除文件后保存this 实例。如果你不想这样,请通过save=False。默认为True

在你正在收听信号的函数my_function2中,它应该是:

instance.image_file.path

【讨论】:

  • 有效!他们都是!非常感谢,特别是详细的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多