replacing a file while uploading in django
Asked Answered
C

1

1

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
Coyne answered 28/7, 2015 at 2:12 Comment(0)
F
6

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)
Flyover answered 28/7, 2015 at 6:47 Comment(2)
Why save=False in delete()? Don't he wants to suppress from db before saving the new one?Weeds
thanks! this works until the .delete () then it throws an maximom recursion errorCoyne

© 2022 - 2024 — McMap. All rights reserved.