Django:输入图像文件的小写文件名

发布于 2024-09-14 00:38:35 字数 273 浏览 1 评论 0原文

我有一个模型:

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to='img')

我正在使用管理员上传海报并保存 Foo 对象。我现在需要找到一种方法在保存之前将文件名小写。例如 POSTER.png 或 Poster.png 或 poster.PNG 应小写为 poster.png。

实现这一目标的最简单方法是什么?

I have a model:

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to='img')

I'm using the admin to upload posters and save Foo objects. I now need to find a way to lowercase the filename before save. For instance POSTER.png or Poster.png or poster.PNG should be lowercased to poster.png.

What would be the easiest way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2024-09-21 00:38:35

FileField.upload_to也可以是可调用的,根据文档中的注释:

这也可以是可调用的,例如函数,将调用该函数来获取上传路径,包括文件名。此可调用必须能够接受两个参数,并返回要传递到存储系统的 Unix 样式路径(带有正斜杠)。将传递的两个参数是:

由于 ImageField继承了 FileField 的所有属性和方法,我认为您可以使用:

def update_filename(instance, filename):
    path_you_want_to_upload_to = "img"
    return os.path.join(path_you_want_to_upload_to, filename.lower())

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to=update_filename)

FileField.upload_to may also be a callable, per this comment in the documentation:

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:

Since ImageField inherits all its attributes and methods from FileField, I think you could use:

def update_filename(instance, filename):
    path_you_want_to_upload_to = "img"
    return os.path.join(path_you_want_to_upload_to, filename.lower())

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to=update_filename)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文