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
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)