简体   繁体   中英

Django. How to programatically rename files uploaded using django-filer

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM