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

懵懂的女人 提交于 2020-01-22 22:54:26

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/2546575/how-to-update-the-filename-of-a-djangos-filefield-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!