I am trying to upload a profile picture when model instance is being created. I want my profile picture to be stored in a folder, that is named according to the instance id, hence once the picture is uploaded I need to create a new dir and move the picture there.
I followed this, which suggests overriding the default save()
method in the model, and this, that proposes to use post_save signal
to save the new file twice.
My current code looks as follows:
class Emp(models.Model):
photo = models.ImageField("Photo", blank=True, null=True, default='default_avatar.png')
def save(self, *args, **kwargs):
# Call standard save
super(Emp, self).save(*args, **kwargs)
if self.photo.path:
initial_path = self.photo.path
new_path = os.path.join(settings.MEDIA_ROOT,
'profile_picture_of_emp_{0}/{1}'.format(self.pk, os.path.basename(initial_path)))
# Create dir if necessary and move file
if not os.path.exists(os.path.dirname(new_path)):
os.makedirs(os.path.dirname(new_path))
os.rename(initial_path, new_path)
# Save changes
super(Emp, self).save(*args, **kwargs)
So this actually moves the file and creates new_path
correctly, however, the self.photo.path
stills refers to the old location and I can't figure out a way to update this new path. The same happens with post_save
signal as it doesn't update the path of moved file. Any suggestions?
Thanks!