如何为用DjangoCKEeditor上传的图像创建uuid4文件名?

2024-05-17 02:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为用django-ckeditor/uploader上传的图像创建随机uid文件名。在

我在settings.py所在的文件夹中创建了utils.py

import uuid

def get_name_uid():
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return filename

我想将这个“随机”文件名添加到settings.py

^{pr2}$

我该怎么做?我不知道如何获取在编辑器中上载的文件名。我应该把文件名从设置.py到utils.py?或者有别的办法吗?在

他们的文件上写着following

``CKEDITOR_UPLOAD_PATH = "uploads/"``

When using default file system storage, images will be uploaded to "uploads" folder in your MEDIA_ROOT and urls will be created against MEDIA_URL (/media/uploads/image.jpg).

If you want be able for have control for filename generation, you have to add into settings yours custom filename generator.

```
# utils.py

def get_filename(filename):
    return filename.upper()
```

```
# settings.py

CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
```

CKEditor has been tested with django FileSystemStorage and S3BotoStorage.
There are issues using S3Storage from django-storages.

Tags: djangopyckeditoruidgetreturnsettingsuuid
1条回答
网友
1楼 · 发布于 2024-05-17 02:37:16

基本上都是在文档中为您详细说明的:

def get_filename(filename):
    return filename.upper()  # returns the uppercase version of filename

因此,示例函数get_filename获取传入的上载文件名,您应该返回希望的文件名。这就是我们所说的callback。在

回调作为参数传入的内容称为“回调签名”,而文档则精确地指定了它获得的内容。在

所以把函数放在makes sense的地方。我会选择mysite/mysite/utils.py。根据教程中概述的结构,在标题“让我们看看startproject创建了什么:”。所以在与settings.py相同的目录中。我将其命名为generate_uuid4_filename,并且mysite/mysite/utils.py将如下所示:

^{pr2}$

现在更新您的settings.py

# Near the rest of the CKEditor variables
CKEDITOR_FILENAME_GENERATOR = '<app_label>.utils.generate_uuid4_filename'

你就完蛋了。祝你好运!在

相关问题 更多 >