Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the filename of a Django's FileField instance?

Here a simple django model:

class SomeModel(models.Model):
    title = models.CharField(max_length=100)
    video = models.FileField(upload_to='video')

I would like to save any instance so that the video's file name would be a valid file name of the title.

For example, in the admin interface, I load a new instance with title "Lorem ipsum" and a video called "video.avi". The copy of the file on the server should be "Lorem Ipsum.avi" (or "Lorem_Ipsum.avi").

Thank you :)

like image 919
user176455 Avatar asked Mar 30 '10 15:03

user176455


1 Answers

If it just happens during save, as per the docs, you can pass a function to upload_to that will get called with the instance and the original filename and needs to return a string to be used as the filename. Maybe something like:

from django.template.defaultfilters import slugify
class SomeModel(models.Model):
    title = models.CharField(max_length=100)
    def video_filename(instance, filename):
        fname, dot, extension = filename.rpartition('.')
        slug = slugify(instance.title)
        return '%s.%s' % (slug, extension) 
    video = models.FileField(upload_to=video_filename)
like image 131
rz. Avatar answered Sep 30 '22 19:09

rz.