【问题标题】:How to create uuid4 file names for images uploaded with Django-CKEeditor?如何为使用 Django-CKEditor 上传的图像创建 uuid4 文件名?
【发布时间】:2017-12-10 11:04:45
【问题描述】:

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

【问题讨论】:

    标签: python django file-upload django-ckeditor


    【解决方案1】:

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

    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'
    

    你就完成了。祝你好运!

    【讨论】:

    • 内部服务器错误:/ckeditor/upload/module_path, class_name = dotted_pa​​th.rsplit('.', 1) AttributeError: 'function' object has no attribute 'rsplit' [06/Jul/2017 14 :48:20] "POST /ckeditor/upload/?CKEditor=id_description&CKEditorFuncNum=1&langCode=en HTTP/1.1" 500 97818
    • 知道为什么会这样吗?
    • 梅尔文不知道?
    • 文档/示例说它是一个字符串(也是例外),把你要使用的'module.function'放在里面。
    • 它是必需的,因为这个插件是自己进行导入的,因此你需要你的应用程序名称,在没有应用程序名称的情况下导入它是行不通的。 (显式总比隐式好)
    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 2022-08-16
    • 2013-02-05
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2016-09-13
    相关资源
    最近更新 更多