飞仙锅建站日志第4篇-添加django-zinnia-ckeditor富文本编辑器

上一篇讲了《飞仙锅建站日志第3篇-换肤django-zinnia-bootstrap》,这一篇讲zinnia另外一个好用的插件,django-blog-zinnia如何添加ckeditor实现原理和配置路径,以及各类插件的使用,大家可以定制出专属于自己的文档编辑器。have fun!

    首先了解一下CKEditor文本编辑器,它是一款旨在简化Web内容编辑的即用(ready for use)的HTML文本编辑器。它是一款所见即所得(WYSIWYG)的编辑器,涵盖了常用的文本编辑功能。CKEditor是一款开源的应用,开发者可以根据实际需求修改源码。

实现原理

    django-blog-zinnia的生态系统提供了对ckeditor编辑器的支持,默认安装zinnia博客正文使用的是Textarea,这时需要使用zinnia-ckeditor进行扩展支持,它将EntryAdminCKEditorForm反向注册到admin.site去,从Form层将TextArea替换成了CkEditor。并没有从model层直接使用models.CkeditorField方法,当然你也可以使用这个方法来实现。

class EntryAdminCKEditorForm(EntryAdminForm):
    """
    Define the CKEditor widget for the content field.
    """
    content = forms.CharField(
        label=_('Content'), required=False,
        widget=CKEditor(config_name=CONFIG_NAME))

class EntryAdminCKEditorMixin(object):
    """
    Mixin adding CKEditor for editing Entry.content field.
    """
    form = EntryAdminCKEditorForm


class EntryAdminCKEditor(EntryAdminCKEditorMixin,
                         EntryAdmin):
    """
    Enrich the default EntryAdmin with CKEditor.
    """
    pass

if ENTRY_BASE_MODEL == 'zinnia.models_bases.entry.AbstractEntry':
    admin.site.unregister(Entry)
    admin.site.register(Entry, EntryAdminCKEditor)

安装配置

    需要下载zinnia-ckeditor、ckeditor、ckeditor_uploader,将源码目录复制到django工程下面,并在settings.py中加入apps

INSTALLED_APPS = [
    ...
    "ckeditor",
    "ckeditor_uploader",
    'zinnia_ckeditor',
    ...
]

    ckeditor提供两个组件,ckeditor、ckeditor_uploader,顾名思义后面一个支持上传文件,需要配置上传目录配置static和media目录,在settings.py中,加入以下代码:

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "ck_static")

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "ck_media")

    配置ckeditor参数,包括文件上传路径,指定图片压缩处理器pillow等。下面重点讲几个有用的配置

  1. 工具栏定制:因为默认的工具栏按钮很少,不方便文档编辑,本文给出最全的按钮,可以按照需要进行删减。
  2. 代码段插件:codesnippet、代码高亮插件autogrow,这个对的程序员展示代码太有用了。
  3. TabSpace配置:默认是不支持,需要指定'tabSpaces': 4, 否则在编辑文档时相当难受。

    在settings.py中,加入以下代码:

from ckeditor.configs import DEFAULT_CONFIG  # noqa

CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"  #处理缩略图
CKEDITOR_THUMBNAIL_SIZE = (300, 300)
CKEDITOR_IMAGE_QUALITY = 40
CKEDITOR_BROWSE_SHOW_DIRS = True
CKEDITOR_ALLOW_NONIMAGE_FILES = True

CUSTOM_TOOLBAR = [
    
    { 'name': 'document',    'items' : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
    { 'name': 'clipboard',   'items' : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
    { 'name': 'editing',     'items' : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { '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' ] },
    { 'name': 'links',       'items' : [ 'Link','Unlink','Anchor' ] },
    
    { 'name': 'insert',      'items' : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak' ] },
    '/',
    { 'name': 'styles',      'items' : [ 'Styles','Format','Font','FontSize' ] },
    { 'name': 'colors',      'items' : [ 'TextColor','BGColor' ] },
    { 'name': 'widgets',     'items':  [ "CodeSnippet",'autogrow'],},#默认没有,新加代码段插件
    { 'name': 'tools',       'items' : [ 'Maximize', 'ShowBlocks','-','About' ] },
    
]

CKEDITOR_CONFIGS = {
    #默认配置
    "default": DEFAULT_CONFIG,
    #自定义配置
    "my-custom-toolbar": {
        "skin": "moono-lisa",
        "toolbar": CUSTOM_TOOLBAR,
        "toolbarGroups": None,
        "extraPlugins": ",".join(["image2", "codesnippet","autogrow"]),#代码块、代码高亮插件
        "removePlugins": ",".join(["image"]),
        "codeSnippet_theme": "xcode",
        'autoGrow_maxHeight ': 1200,
        'tabSpaces': 4,  #可以使用tabspace缩进
        "height": 291,
        "width": 900,
        "filebrowserWindowWidth": 940,
        "filebrowserWindowHeight": 725,
    },
}

引用ckeditor的自定义工具栏,在zinnia_ckeditor/admin.py指定配置my-custom-toolbar

#这个是读取settings的配置,否则就默认
CONFIG_NAME = 'my-custom-toolbar'
CKEDITOR_CONFIG = getattr(settings, 'CKEDITOR_CONFIGS', {})
if CONFIG_NAME not in CKEDITOR_CONFIG:
    CONFIG_NAME = 'default'

结语

    到这里,使用ckeditor基本上已经可以应对大部分的文档编辑工作了,希望对你有用。

评论列表

tufei

自己做盖一楼

2021年8月16日 19:26回复

tufei

测试

2021年8月16日 19:29回复

tufei

测试

2021年8月16日 19:30回复

新的评论

清空