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
save=False
indelete()
? Don't he wants to suppress from db before saving the new one? – Weeds