django-ckeditor上传图片到七牛云OSS

参考信息

django-ckeditor本地图片上传功能:https://www.jianshu.com/p/882cf85b604f
django+ckeditor+七牛云,图片上传到七牛云:http://xieboke.net/article/56/

使用

1. 安装django-ckeditor

pip install django-ckeditor

2. setting.py配置INSTALLED_APPS

3. 编写ckeditor_storage.py

import datetime
import uuid
from django.core.files.storage import Storage
from qiniu import Auth, put_data
from joyoo.settings import QINIU_ACCESS_KEY, QINIU_SECRET_KEY, QINIU_BUCKET_DOMAIN, QINIU_BUCKET_NAME


class StorageObject(Storage):
    def __init__(self):
        self.now = datetime.datetime.now()
        self.file = None

    def _new_name(self, name):
        new_name = "file/{0}/{1}.{2}".format(self.now.strftime("%Y/%m/%d"), str(uuid.uuid4()).replace('-', ''),
                                             name.split(".").pop())
        return new_name

    def _open(self, name, mode):
        return self.file

    def _save(self, name, content):
        """
        上传文件到七牛
        """
        # 构建鉴权对象
        q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
        token = q.upload_token(QINIU_BUCKET_NAME)
        self.file = content
        file_data = content.file
        ret, info = put_data(token, self._new_name(name), file_data.read())

        if info.status_code == 200:
            base_url = 'http://%s/%s' % (QINIU_BUCKET_DOMAIN, ret.get("key"))
            # 表示上传成功, 返回文件名
            return base_url
        else:
            # 上传失败
            raise Exception("上传七牛失败")

    def exists(self, name):
        # 验证文件是否存在,因为会去生成一个新的名字存储到七牛,所以没有必要验证
        return False

    def url(self, name):
        # 上传完之后,已经返回的是全路径了
        return name

4. setting.py中设置ckeditor

# 图片保存路径
MEDIA_URL = "/media/" 
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
CKEDITOR_UPLOAD_PATH = "uploads/"    # 图片ckeditor文件上传路径, 这里使用七牛云存储,不填
# CKEDITOR_IMAGE_BACKEND = 'pillow'  # 注释掉就是禁止生成缩略图,传七牛云要注释掉

# 七牛云OSS相关配置
QINIU_ACCESS_KEY = ''
QINIU_SECRET_KEY = ''
QINIU_BUCKET_DOMAIN = ''
QINIU_BUCKET_NAME = ''

# OSS配置
DEFAULT_FILE_STORAGE = 'blog.ckeditor_storage.QiniuyunStorageObject'

5. setting.py中配置功能项和样式

# ckeditor配置功能项和样式
CKEDITOR_CONFIGS = {
    # django-ckeditor默认使用default配置
    'default': {
        # 编辑器宽度自适应
        'width': 'auto',
        'height': '400px',
        
        'update': ['Image', 'Update', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
        'skin': 'moono',
        'toolbar_Basic': [
            ['Source', '-', 'Bold', 'Italic']
        ],
        # 工具栏按钮
        'toolbar_YourCustomToolbarConfig': [
            {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
            {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
            {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
            {'name': 'forms',
             'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
                       'HiddenField']},
            '/',
            {'name': 'basicstyles',
             'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
            {'name': 'paragraph',
             'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
                       'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
                       'Language']},
            {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
            {'name': 'insert',
             'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
            {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
            {'name': 'colors', 'items': ['TextColor', 'BGColor']},
            {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']},
            {'name': 'yourcustomtools', 'items': [
                # 自定义控件
                'Preview',
                'Maximize',
            ]},
        ],
        # 工具栏风格
        'toolbar': 'YourCustomToolbarConfig',  # put selected toolbar config here
        # tab键转换空格数
        'tabSpaces': 4,
        # 添加 Prism 相关插件
        'extraPlugins': ','.join(
            [
                # your extra plugins here
                'div',
                'autolink',
                'autoembed',
                'embedsemantic',
                'autogrow',
                # 'devtools',
                'widget',
                'lineutils',
                'clipboard',
                'dialog',
                'dialogui',
                'elementspath'
            ]),
    }
}

6. 设置model.py,使用RichTextUploadingField字段

7. 设置urls.py

from django.conf.urls import url,include
urlpatterns = [
    url(r'ckeditor/', include('ckeditor_uploader.urls')),
]

8. 测试

image

posted @ 2021-07-27 18:33  SonnyZhang  阅读(305)  评论(0编辑  收藏  举报