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

时间:2017-07-06 12:29:02

标签: python django file-upload django-ckeditor

我想为使用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吗?或者有不同的方法来做到这一点吗?

他们的文档说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.

1 个答案:

答案 0 :(得分:5)

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

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_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'

你已经完成了。祝你好运!