1. 程式人生 > >django部落格開發:新增富文字編輯器ckeditor

django部落格開發:新增富文字編輯器ckeditor

Markdown用的不太習慣,於是決定新增一個富文字編輯器。ckeditor是一個老牌的編輯器,GitHub上有一個第三方模組django-ckeditor封裝了所有功能,把import到我們的專案裡,然後設定一下引數,就可輕鬆使用了。

EDIT:通過網友反應的一些問題,以及後來我對djangk-ckeditor的深入使用,決定對本文重新編輯一下,讓各位學友少踩一些坑,同時增加一些功能的介紹。

開發環境: Python 3.5、Django 1.10

安裝

使用pip安裝 django-ckeditor 和 pillow,pillow用於生成縮圖,用來在編輯器裡瀏覽上傳的圖片

pip install django-
ckeditor pip install pillow

QUICK START

在 project/settings.py 裡進行如下設定:

INSTALLED_APPS = [
    'ckeditor',
    'ckeditor_uploader',
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CKEDITOR_UPLOAD_PATH = 'upload/'
CKEDITOR_IMAGE_BACKEND = 'pillow'

1. 首先將 'ckeditor'和 'ckeditor_uploader'加入到INSTALLED_APPS中,

2. 設定 MEDIA_ROOT 和 MEDIA_URLCKEDITOR_UPLOAD_PATH = 'upload/',圖片將上傳到專案下的media/upload路徑下,圖片的url是 /media/upload/

3. 設定CKEDITOR_IMAGE_BACKEND = 'pillow', 用於生成圖片縮圖,在編輯器裡瀏覽上傳的圖片


4. 在project/urls.py裡,加入 ckeditor_uploader.url

from django.conf.urls import url,include
from django.conf.urls.static import static
from django.
conf import settings from django.contrib import admin urlpatterns = [ url(r'', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #沒有這一句無法顯示上傳的圖片

注意

在開發環境裡debug模式下,static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 這句是必不可少的,沒有的話,你上傳的圖片將無法顯示。將這段程式碼Python shell裡執行一下,會發現其實就是解析了media_url

當我們在伺服器部署時,需要用nginx來配置靜態資源,在nginx的配置檔案裡

location /media {
                alias /path-to/media;
        }

4. 在blog/models.py的Post類,讓正文欄位使用 RichTextUploadingField()

from ckeditor_uploader.fields import RichTextUploadingField

class Post(models.Model):
    content = RichTextUploadingField(verbose_name='正文')

5. 最後還是不要忘了遷移資料庫

pyhton manage.py makemigrations
python manage.py migrate

進入admin後臺去新增文章,就會發現編輯器已經在那裡了,是不是很開心啊

django-ckeditor

其他可選配置

CKEDITOR_ALLOW_NONIMAGE_FILES = False 不允許非圖片檔案上傳,預設為True

CKEDITOR_BROWSE_SHOW_DIRS = True 在編輯器裡瀏覽上傳的圖片時,圖片會以路徑分組,日期排序

CKEDITOR_RESTRICT_BY_USER = True 限制使用者瀏覽圖片的許可權,只能瀏覽自己上傳的圖片,圖片會傳到以使用者名稱命名的資料夾下,超級管理員依舊可以看所有圖片

NOTICE

django-ckeditor預設的只允許管理員(staff member)上傳圖片,當普通使用者使用編輯器時(比如評論區、留言板、發帖子),如果要使他們上傳圖片的話,需要對django-ckeditor的原始碼進行修改

在ckeditor_uploader/urls.py裡,它的upload 和 browse方法用了staff_member_required裝飾器,把它換成login_required裝飾器即可

if django.VERSION >= (1, 8):
    urlpatterns = [
        url(r'^upload/', login_required(views.upload), name='ckeditor_upload'),
        url(r'^browse/', never_cache(login_required(views.browse)), name='ckeditor_browse'),
    ]

自定義編輯器

如果想要自定義編輯器,新增或刪除一些按鈕的話,需要在settings.py裡設定 CKEDITOR_CONFIGS

CKEDITOR_CONFIGS = {
    # 配置名是default時,django-ckeditor預設使用這個配置
    'default': {
        # 使用簡體中文
        'language':'zh-cn',
        # 編輯器的寬高請根據你的頁面自行設定
        'width':'auto',
        'height':'150px',
        'image_previewText':' ',
        'tabSpaces': 4,
        'toolbar': 'Custom',
        # 新增按鈕在這裡
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline', 'Format', 'RemoveFormat'],
            ['NumberedList', 'BulletedList'],
            ['Blockquote', 'CodeSnippet'],
            ['Image', 'Link', 'Unlink'],
            ['Maximize']
        ],
        # 外掛
        'extraPlugins': ','.join(['codesnippet','uploadimage','widget','lineutils',]),
    }
}

當配置名稱是 'default',django-ckeditor會預設使用這個配置,CKEDITOR_CONFIGS裡可以新增多個配置,比如

CKEDITOR_CONFIGS = {
    # 配置名是default時,django-ckeditor預設使用這個配置
    'default': {

    }  
    # 名為custom的配置  
    'custom': {

    }
}

當需要使用非預設配置是,需要在 RichTextUploadingField() 裡指定該配置名稱

class Post(models.Model):
    content = RichTextUploadingField(config_name='custom')

新增程式碼功能

寫技術部落格的話,我們的編輯器自然需要新增程式碼塊的功能。需要用到外掛codesnippet,ckeditor的外掛放在了ckeditor/static/ckeditor/ckeditor/plugins/路徑下。

當我們新增一個功能外掛時,需要在CKEDITOR_CONFIGS裡的extraPlugins對應的value裡新增該外掛的名字(名字字母小寫),如果該外掛還有相對應的按鈕,則在toolbar對應的value裡新增名字(首字母大寫),以codesnippet為例,在下面程式碼的第16行和21行分別添加了 'CodeSnippet' 和 'codesnippet'

NOTICE

在21行的extraPlugins裡還添加了 'uploadimage',這個外掛的作用是允許使用者直接在編輯器裡貼上(ctrl + v)圖片

CKEDITOR_CONFIGS = {
    # 配置名是default時,django-ckeditor預設使用這個配置
    'default': {
        # 使用簡體中文
        'language':'zh-cn',
        # 編輯器的寬高請根據你的頁面自行設定
        'width':'730px',
        'height':'150px',
        'image_previewText':' ',
        'tabSpaces': 4,
        'toolbar': 'Custom',
        # 新增按鈕在這裡
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline', 'Format', 'RemoveFormat'],
            ['NumberedList', 'BulletedList'],
            ['Blockquote', 'CodeSnippet'],
            ['Image', 'Link', 'Unlink'],
            ['Maximize']
        ],
        # 外掛
        'extraPlugins': ','.join(['codesnippet','uploadimage','widget','lineutils',]),
    }
}

程式碼高亮、程式碼行數  

從ckeditor官網下載 外掛prism(點這裡直接下載),然後將其解壓到ckeditor/static/ckeditor/ckeditor/plugins路徑下,同樣的我們需要在CKEDITOR_CONFIGS裡將extraPlugins對應的value里加入外掛 'prism' 和另外兩個外掛"lineutils""widget" ,這兩個外掛無須下載,在django-ckeditor中已經有了

'extraPlugins': ','.join(['codesnippet','uploadimage','prism','widget','lineutils',]),

 去prismjs官網下載css檔案,選擇你喜歡的主題,勾選支援的語言,以及別忘選擇line-numbers功能,下載後把他解壓到static/blog/css

然後在模板中引用靜態檔案

<script src="{% static 'ckeditor/ckeditor/plugins/prism/lib/prism/prism_patched.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'blog/css/prism.css' %}">

在admin以外的地方使用django-ckeditor

如果在admin以外的地方使用django-ckeditor,比如

在渲染表單的那個頁面需要引入 ckeditor-init.js 和 ckeditor.js 兩個檔案,否則編輯器無法顯示

{% load static %}
<script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script>
<script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>

當然還有另外一種方法,本質上跟前者一樣的

<form>
    {{ myform.media }}
    {{ myform.as_p }}
    <input type="submit"/>
</form>

編輯框響應式

1. 需要CKEDITOR_CONFIGS裡設定 'width': 'auto'

2.

<script>
    $(".django-ckeditor-widget").removeAttr('style');
</script>

原文地址:

http://www.aaron-zhao.com/post/1/#在admin以外的地方使用django-ckeditor