首页 > 代码库 > 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中添加富文本编辑器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。