Reputation: 4743
Let's say I am selecting 10 files to be uploaded using django-filer. They initially have very random names. I'd like to have a set of rules according to which they ought to be renamed and only then passed for further processing (thumbnails etc.).
I need to actually rename everything, especially filename, not just Image model name.
I tried catching pre_save signal for Image model and altering instance.original_filename but that's not renaming a filename. Or maybe should I subclass and override something from filer package?
I'd be grateful for code example cause this is a little bit to hard for me.
Upvotes: 1
Views: 1007
Reputation: 5177
I used form_valid(self, form)
in views.py to process and manipulate my images. The complete code is a bit long and very specific, but I'll post a few snipplets which should show the idea of how to generate filenames:
def form_valid(self, form):
upload = self.request.FILES['profilbild_original'] #coming from a very simple form
self.request.user.student.profilbild_original = upload
self.request.user.student.save()
#no renaming was required here, but now I did some work:
inputfilepath = os.path.join(my_app.settings.MEDIA_ROOT, profilbild_path(self.request.user, str(upload)))
original = Image.open(inputfilepath)
original.thumbnail((200,200), Image.ANTIALIAS)
filename = str(upload)+'.thumbnail_200_200_aa.jpg'
filepath = profilbild_path(self.request.user, filename)
filepath = os.path.join(my_app.settings.MEDIA_ROOT, filepath)
original.save(filepath, 'JPEG', quality=90)
self.request.user.student.profilbild = profilbild_path(self.request.user, filename).replace("\\", "/")
self.request.user.student.save()
return super(ProfilbildView, self).form_valid(form)
profilbild_path
is a function according to https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.upload_to :
def profilbild_path(instance, filename):
return os.path.join('profilbilder', str(instance.id), filename)
I hope this gives you some clues.
Upvotes: 1