How to update Django FileField instance file name?

Here's 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 file name is the videocorrect file name title.

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

Thank:)

+5
source share
1 answer

, docs, upload_to, , , . , - :

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)
+8

All Articles