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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章