Wednesday, 15 April 2015

python 2.7 - Update FileField filename after uploaded file saved (Django) -



python 2.7 - Update FileField filename after uploaded file saved (Django) -

how alter filename of media file (user-uploaded file) in django after it's been saved?

i understand if want as it's beingness uploaded can follow solution in questions this, i'm talking changing names of images in database.

i have tried overriding name attribute of imagefilefield , saving model, not impact file itself. breaks reference because imagefilefield pointing @ new name file still has old one.

using same illustration model linked question:

class somemodel(models.model): title = models.charfield(max_length=100) video = models.filefield(upload_to='video')

this not work:

>>> m in somemodel.objects.all(): ... m.video.name = 'new_video_name.avi' ... m.save()

what should doing here?

there no magic , easy way it. when load object database (the loop), name of file referenced video attribute loaded database too. can't alter , create underlying file alter it's name.

in order accomplish name alter both physical file , reference in database you'll have rename physical file manually. should work:

import os class somemodel(models.model): file_field = ... def rename(self, new_name): old_path = self.file_field.path self.file_field.name = new_name os.rename(old_path, self.file_field.path) self.save() m in somemodel.objects.all(): new_name = compute_new_filename(m) m.rename(new_name)

note simplified version , may want handling possible io errors when doing os.rename().

also code assumes using filesystemstorage , not other custom storage class. in case, implementation need adapted particular storage mechanism.

django python-2.7

No comments:

Post a Comment