Here a simple django model:
这里有一个简单的django模型:
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").
例如,在管理界面中,我加载了一个标题为“Lorem ipsum”的新实例和一个名为“video.avi”的视频。服务器上的文件副本应为“Lorem Ipsum.avi”(或“Lorem_Ipsum.avi”)。
Thank you :)
谢谢 :)
1 个解决方案
#1
8
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:
如果它只是在保存期间发生,根据文档,您可以将函数传递给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)
#1
8
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:
如果它只是在保存期间发生,根据文档,您可以将函数传递给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)