如何更新Django FileField实例的文件名? [英] How to update the filename of a Django's FileField instance?

查看:85
本文介绍了如何更新Django FileField实例的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的Django模型:

Here a simple django model:

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

我想保存任何实例,以使video的文件名成为title的有效文件名.

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

例如,在管理界面中,我加载了一个标题为"Lorem ipsum"和名为"video.avi"的视频的新实例.服务器上文件的副本应为"Lorem Ipsum.avi"(或"Lorem_Ipsum.avi").

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").

谢谢:)

推荐答案

如果只是在保存期间发生,请按照

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)

这篇关于如何更新Django FileField实例的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆