3

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

utils.py在同一个文件夹中创建了settings.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 吗?还是有其他方法可以做到这一点?

他们的文档说明如下

``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.
4

1 回答 1

6

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

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

因此,示例函数get_filename获取传入的上传文件名,并且您应该返回您想要的文件名。这就是我们所说的回调

回调作为参数传入的内容称为“回调签名”,文档清楚地指定了它得到的内容。

所以把函数放在有意义的地方。我会选择mysite/mysite/utils.py教程中概述的结构,在标题“让我们看看 startproject 创建了什么: ”下。所以在同一个目录下settings.py。我会命名它generate_uuid4_filenamemysite/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'

你完成了。祝你好运!

于 2017-07-06T13:41:25.793 回答