在 Django 中上传时替换文件

replacing a file while uploading in django

我的 models.py 中有以下代码:

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

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

当我上传第二张图片时,我希望删除第一张图片。这样每辆车总是只有一张图片 class。相反,当我上传第二个时,django 会在文件名末尾添加一些字符。

我想到了这个

filename = "%s.%s" %

旧图像会被替换吗?

有什么建议吗?

谢谢!

编辑

感谢 zxzak 我做到了,对我来说它的工作方式略有不同(使用 os.remove(path) ):

    try:
        this = Company.objects.get(id=self.id)
        if this.image_file:
            os.remove(this.image_file.path)
    except ObjectDoesNotExist:
        pass

您可能想要覆盖保存方法以引入此行为。此代码每次都会删除前面的 image_field,除非正在创建 Cars 实例。

from django.core.exceptions import ObjectDoesNotExist

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


    def save(self, *args, **kwargs):
        try:
            this = Cars.objects.get(id=self.id)
            if this.image_file:
                this.image_file.delete()   
        except ObjectDoesNotExist: 
            pass        
        super(Cars, self).save(*args, **kwargs)