gpt4 book ai didi

python - 如何为使用 Django-CKEditor 上传的图像创建 uuid4 文件名?

转载 作者:太空宇宙 更新时间:2023-11-03 14:04:46 24 4
gpt4 key购买 nike

我想为使用 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:

CKEDITOR_FILENAME_GENERATOR = get_name_uid()

我该怎么做?我不确定如何获取在编辑器中上传的文件名。我应该将文件名从 settings.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.

最佳答案

文档中基本上都为您详细说明了:

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 看起来像这样:

import uuid
import os.path

def generate_uuid4_filename(filename):
"""
Generates a uuid4 (random) filename, keeping file extension

:param filename: Filename passed in. In the general case, this will
be provided by django-ckeditor's uploader.
:return: Randomized filename in urn format.
:rtype: str
"""
discard, ext = os.path.splitext(filename)
basename = uuid.uuid4().urn
return ''.join(basename, ext)

现在更新您的 settings.py:

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

你就完成了。祝你好运!

关于python - 如何为使用 Django-CKEditor 上传的图像创建 uuid4 文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44948917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com