0

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!

1
  • 1
    Did you try self.photo = new_path;super(Emp, self).save(*args, **kwargs) at end ?\ Commented Jan 18, 2018 at 11:54

1 Answer 1

1

Add

my_new_path = 'profile_picture_of_emp_{0}/{1}'.format(self.pk, os.path.basename(initial_path)) self.photo = my_new_path; super(Emp, self).save(*args, **kwargs) 

at the end.

Sign up to request clarification or add additional context in comments.

4 Comments

I get DataError: value too long for type character varying(100) (my picture name is 15 chars long), therefore I assume it sets a photo.name instead of a path
Sorry, I checked it and it actually updates the path, however I get the latter error during the save()
Add max_length=200 and try after migrate
haha I was about to write that! It works! Thank you very much! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.