Django image upload to dynamic path
A regular field to store an image in a Django model looks like this
class MemberPhotos(models.Model):
member = models.ForeignKey(Member)
photo = models.ImageField(upload_to="photos/members/")
The path "photos/members/" is always relative to settings.MEDIA_ROOT
. But what if each member should have their own sub-directory for their own photos, and the filename should be converted into a safe UUID value? Something like "photos/members/ID/UUID.jpg".
The upload_to
argument to ImageField() can be a function that returns the final file path and name, still relative to MEDIA_ROOT.
def get_member_upload_to(instance, filename):
new_filename = '{}.{}'.format(uuid.uuid4, filename.split('.')[-1])
return "photos/members/{}/{}".format(instance.member.id, new_filename)
class MemberPhotos(models.Model):
member = models.ForeignKey(Member)
photo = models.ImageField(upload_to=get_member_upload_to)
The upload_to function takes two arguments:
- the instance of the model to which the file is being attached
- the original file name of the uploaded file
It is, however, not possible to use the instance's own ID, because the instance has not been saved yet and therefore it has no ID value assigned yet.