0%

「Django富文本」django-ckeditor的使用

之前在副文本上一直使用百度家的UEditor,但是官方在Django以及python3.X上没有做维护,所以换上了ckeditor,使用下来还算方便。

环境信息:

  • Django 2.0.1
  • django-ckeditor 5.4.0

正文:

  1. 用pip安装ckeditor:

    1
    pip install django-ckeditor
  2. settingsINSTALLED_APPS注册:

    1
    2
    3
    4
    5
    6
    7
    8
    INSTALLED_APPS = [
    ...

    'ckeditor',
    'ckeditor_uploader', # 如果富文本中允许用户上传图片/文件到后台,则需要加上

    ...
    ]
  3. 配置上传文件路径(如果用到上传功能):
    ckeditor的上传路径是将media的路径后边拼接upload_path,也就是说按照下边的配置,最终的上传路径为/media/uploads/

    1
    2
    3
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    CKEDITOR_UPLOAD_PATH = "uploads/"
  4. 富文本url配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from django.urls import include, re_path

    urlpatterns = [
    ...

    re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), # Django2.0要用're_path'

    ...
    ]
  5. 在settings中按需定制自己的富文本面板(非必须):
    可以按照自己的喜好,定制富文本的编辑工具面板,下边这个是我花了点时间选出了一些常用以及实用的功能。其中具体参数含义可以到官方文档查询。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    CKEDITOR_CONFIGS = {
    'default': {
    'toolbar_ToolbarConfig': [
    {'name': 'basic', 'items': [
    'Font', 'FontSize', 'BGColor', 'TextColor',
    '-',
    'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock',
    '-',
    'Bold', 'Italic', 'Underline', 'Strike', 'Undo', 'Redo',
    '-',
    'Strike', 'Subscript', 'Superscript',
    '-',
    'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar',
    ]},
    '/',
    {'name': 'custom', 'items': [
    'Source',
    '-',
    'Preview', 'Maximize',
    ]}
    ],
    'toolbar': 'ToolbarConfig',
    'width': '100%',
    }
    }
  1. field的使用方式:
    1
    2
    3
    4
    5
    6
    7
    from django.db import models
    from ckeditor.fields import RichTextField
    from ckeditor_uploader.fields import RichTextUploadingField

    class Post(models.Model):
    content_without_upload = RichTextField() # 不带上传功能的富文本
    content_with_upload = RichTextUploadingField() # 带上传功能的富文本(需要先在INSTALL_APP中声明)
  1. 效果:

    django-ckeditor后台效果

  2. 后记:
    在前后端分离的开发过程中,富文本内所插入的图片需要返回绝对路径,查了许多文档,ckeditor没有像百度的UEditor一样把url_prefix放出来,方便设置。后来我摸索了一下,改动了一下源码就可以实现功能了。文件路径ckeditor_uploader/util.py中的get_media_url(path),具体如下:

    1
    2
    3
    4
    5
    6
    def get_media_url(path):
    """
    Determine system file's media URL.
    """
    url_prefix = hasattr(settings, 'CKEDITOR_URL_PREFIX') and settings.CKEDITOR_URL_PREFIX or ''
    return url_prefix + default_storage.url(path)

    随后只需要在settings中加入:

    1
    CKEDITOR_URL_PREFIX = 'https://actmerce.github.io'

参考: