replacing a file while uploading in django

六眼飞鱼酱① 提交于 2019-12-08 09:52:50

问题


I have the following code in my 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)

When I upload a second image I want the first one to be deleted. So that there will always be only one image per car class. Instead, when I upload a second one, django adds some characters to the end of the filename.

I thought with this

filename = "%s.%s" %

the old image would be replaced?

Any advice?

Thanks !

EDIT

Thanks to zxzak I made it, for me it worked slightly different though (with os.remove(path) ):

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

回答1:


You might want to override the save method in order to introduce this behaviour. This code will delete the previous image_field every time except when a Cars instance is being created.

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)


来源:https://stackoverflow.com/questions/31666309/replacing-a-file-while-uploading-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!