首页 > 代码库 > Django中添加富文本编辑器

Django中添加富文本编辑器

使用的是CKeditor这个模块

1.安装:

pip install django-ckeditor

2.将ckeditor注册到settings.py文件中, 并添加ckeditor的url到你项目的urls.py文件中

INSTALLED_APPS = [
    ...
    ckeditor
]


urlpatterns = [
  ...
  url(r‘^ckeditor/‘, include(‘ckeditor_uploader.urls‘)),
]

3.在models.py文件中使用ckeditor的富文本字段RichTextField替换TextField就行,用法不变。

from ckeditor.fields import RichTextField
...
content = RichTextField(verbose_name=u内容)

 

4.在settings.py文件中写入cdeditor的配置

# ckeditor config
CKEDITOR_UPLOAD_PATH = article_files/
CKEDITOR_JQUERY_URL =js/jquery-3.2.1.min.js
CKEDITOR_IMAGE_BACKEND = pillow
CKEDITOR_CONFIGS = {
    default: {
        language: zh-cn,
        toolbar_YourCustomToolbarConfig: [

            {name: clipboard, items: [Undo, Redo, -, Cut, Copy, Paste, PasteText, PasteFromWord]},
            {name: paragraph, items: [NumberedList, BulletedList, -, Outdent, Indent, -, Blockquote]},
            {name: insert, items: [Image, Table, HorizontalRule, Smiley]},
            {name: links, items: [Link, Unlink, Anchor]},
            {name: editing, items: [Find, Replace, -]},
            {name: tools, items: [Maximize]},
            /,
            {name: styles, items: [Format, Font, FontSize]},
            {name: basicstyles,
             items: [Bold, Italic, Underline, Strike, -, RemoveFormat]},
            {name: colors, items: [TextColor, BGColor]},
            {name: paragraph,
             items: [JustifyLeft, JustifyCenter, JustifyRight, JustifyBlock]},
            {name: document, items: [Source]},
        ],
        toolbar: YourCustomToolbarConfig,  # put selected toolbar config here
        width: 100%,
        tabSpaces: 4,
        extraPlugins: ,.join([
            uploadimage,  # the upload image feature
            # your extra plugins here
            div,
            autolink,
            autoembed,
            embedsemantic,
            autogrow,
            widget,
            lineutils,
            clipboard,
            dialog,
            dialogui,
            elementspath
        ]),
    }
}
CKEDITOR_ALLOW_NONIMAGE_FILES = False
CKEDITOR_BROWSE_SHOW_DIRS = True

5.如果要实现编辑器中图片上传的功能,还需要一些配置:

  在settings.py文件中注册‘ckeditor_uploader‘

  

INSTALLED_APPS = [

    ckeditor,
    ckeditor_uploader
]

  我在上面的配置中写一个路径:CKEDITOR_UPLOAD_PATH = ‘article_files/‘ 

  这是一个相对路径,你需要配置好media:

# media_confige
MEDIA_URL = /media/
MEDIA_ROOT = os.path.join(BASE_DIR, media)

  之后上传图片的保存路径就是‘/media/article_files/...‘

  在models.py中就需要使用RichTextUploadingField字段

  

from ckeditor_uploader.fields import RichTextUploadingField
。。。
class MyModel(models.Model):
    content = RichTextUploadingField(verbose_name=u内容)

 

文档:https://github.com/django-ckeditor/django-ckeditor

Django中添加富文本编辑器