6

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 :)

user176455
  • 685
  • 1
  • 10
  • 21

1 Answers1

11

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)
serg
  • 106,723
  • 76
  • 306
  • 327
rz.
  • 19,435
  • 10
  • 53
  • 47