django-ckeditor

2019-08-27  本文已影响0人  M_派森

一、前言

之前写了个测试报告的模版页面,后期同时需要上传图片,就需要使用富文本编辑器了,这里选择了django-ckeditor。

二、操作步骤

1、安装

pip install django-ckeditor

pip install pillow

2、配置

在settings.py中添加配置:

(1)配置1:

settings配置

MEDIA_URL ="/static/media/"

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

CKEDITOR_UPLOAD_PATH ="upload/"

CKEDITOR_IMAGE_BACKEND ="pillow"

CKEDITOR_CONFIGS = {

'default': {

'toolbar': (

['div','Source','-','Save','NewPage','Preview','-','Templates'],

['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print','SpellChecker','Scayt'],

['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],

['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],

['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],

['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],

['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],

['Link','Unlink','Anchor'],

['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],

['Styles','Format','Font','FontSize'],

['TextColor','BGColor'],

['Maximize','ShowBlocks','-','About','pbckcode'],

),

# 插件

        'extraPlugins':','.join(['codesnippet','uploadimage','widget','lineutils',]),

}

}

(2)配置2:

install_apps配置

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'ckeditor',

'ckeditor_uploader'

]

在urls.py添加配置:

urls配置

urlpatterns = [

url(r'^ckeditor/', include('ckeditor_uploader.urls')),

]

3、至此应可以使用后台管理进行富文本编辑了

后台管理富文本编辑

三、没有结束

当然,如果以上能够满足你的需求,就不需要往下看了,但是我的需求以上是不能满足的,那么继续。我们看看如何将这个富文本添加到正常的前端页面吧。

1、配置

以上的配置还是需要的,不再赘述。

2、继续配置

这里我遇到了一个坑,不管如何按照网上配置都无法正常加载出页面来,而且加载出来也无法进行上传图片。

(1)前端页面加载js配置

注意:这里有连个js文件很重要,如下

ckeditor-init.js

keditor.js

这两个文件不注意根本想不到怎么弄,因为以上在后台管理应用很正常,为啥在前端就无法使用了呢?继续配置。

我是这么处理的,将下面文件拷贝放在static目录下:

js文件

因为js文件就在这里面:

js文件 static下的js文件

这样就可以继续往下走了:

页面配置加载js文件

<script src="{% static 'ckeditor/ckeditor-init.js' %}" data-ckeditor-basepath="/static/ckeditor/ckeditor/" id="ckeditor-init-script"></script>

<script src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script>

(2)前端页面富文本框配置

在前端页面加上这一句:

<textarea class="ckeditor" cols="50" id="editor1" rows="100" name="goodsdesc"></textarea>

不过这样只是一个富文本框而已,就像这样:

原始富文本框

(3)ckeditor配置

格式修饰配置

在这个文件里可以对富文本框进行一系列配置,这里列出我的配置:

ckeditor配置

CKEDITOR.editorConfig = function( config ) {

config.language = 'zh-cn';

config.uiColor = '';

config.extraPlugins = 'image'; config.filebrowserUploadUrl = '/upload-image/'; config.toolbar = [ { name: 'document', items: ['Source', '-', 'Preview', 'Print', '-'] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'Styles'] }, '/', { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['Image', 'Flash', 'Table'] }, { name: 'tools', items: ['ShowBlocks'] } ]; config.removeDialogTabs = 'image:advanced;image:Link';//隐藏超链接与高级选项 config.toolbarCanCollapse = true; config.image_previewText=' ';};

格式自己调整下吧,这里面“config.filebrowserUploadUrl ='/upload-image/';“这个需要自己填写自己的url地址,就是一个上传图片的方法:

上传图片方法

@csrf_exempt

def upload_image(request):

    if request.session.get('is_login', None) is None:

        return redirect("/userlogin/index/")

    if request.method == 'POST':

        # callback = str(request.GET.get('CKEditorFuncNum'))

        callback = str(1)

        try:

            path = "static/media/upload/photos/" + time.strftime("%Y%m%d%H%M%S",time.localtime())

            f = request.FILES["upload"]

            file_name = path + "_" + f.name

            des_origin_f = open(file_name, "wb+")

            for chunk in f:

                des_origin_f.write(chunk)

            des_origin_f.close()

        except Exception as e:

            print(e)

        res = r"<script>window.parent.CKEDITOR.tools.callFunction("+callback+",'/"+file_name+"', '');</script>"

       HttpResponse(res)

        return JsonResponse({"uploaded": 1, "fileName": time.strftime("%Y%m%d%H%M%S",time.localtime()) + '_' + f.name, "url": "http://" + request.get_host() + "/" + file_name}) else: raise Http404()

格式自己调整下,url路径:

url(r'^upload-image', books.upload_image, name='upload_image'),

(4)效果

修饰后富文本框 上传界面

至此完成,不过上传图片的方法需要好好看下吧,里面涉及到settings.py文件里的static路径等等,有问题再看吧。

上一篇 下一篇

猜你喜欢

热点阅读