欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django添加富文本编辑器

程序员文章站 2022-07-14 22:42:20
...
  1. 安装 pip install django-ckeditor。
  2. 在settings.py中注册应用并添加相应配置
INSTALLED_APPS = [
    ...
    'ckeditor',
]

CKEDITOR_CONFIGS = {
    'comment_ckeditor': {
        'toolbar': 'custom',
        'toolbar_custom': [
            ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
            ["TextColor", "BGColor", 'RemoveFormat'],
            ['NumberedList', 'BulletedList'],
            ['Link', 'Unlink'],
            ["Smiley", "SpecialChar", 'Blockquote'],
        ],
        'extraPlugins': 'codesnippet',
        'width': 'auto',
        'height': '180',
        'tabSpaces': 4,
        'removePlugins': 'elementspath',
        'resize_enabled': False,
    },

    'default': {
        'toolbar': 'full',
        'height': 300,
        'width': 'auto',
        'extraPlugins': 'codesnippet',
    },
}
  1. 配置model, 把字段改成RichTextField
from ckeditor.fields import RichTextField

class A(model.Model):
    ...
    content = RichTextUploadingField()
    ...
  1. 添加上传图片功能,安装pip install pillow
  2. 配置settigns.py
INSTALLED_APPS = [
    ...
    'ckeditor',
    'ckeditor_uploader',

]

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

#配置ckeditor
CKEDITOR_UPLOAD_PATH = 'upload/'
  1. 配置url
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ...
    path('ckeditor', include('ckeditor_uploader.urls')),
    ...
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

效果如图:
django添加富文本编辑器