KindEditor安装配置

WEB开发离不开富文本编辑器,KindEditor和CKEditor是两款不错的第三方插件。

1.kindeditor下载

http://kindeditor.net/down.php

2.目录结构(删除多余的文件)

python+django常用富文本插件使用配置(ckeditor,kindeditor)

3.settings.py和urls.py配置
  在settings.py 中设置MEDIA_ROOT 目录

 #文件上传配置

   MEDIA_ROOT = os.path.join(BASE_DIR,’uploads’)

 # urls.py 配置

   url(r'^admin/uploads/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),

     url(r'^uploads/(?P<path>.*)$', views.static.serve, {‘document_root’: settings.MEDIA_ROOT, }),

4.upload.py 文件

  该文件存放在根目录同名文件夹下

  project---project----upload.py

# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import os
import uuid
import json
import datetime as dt

@csrf_exempt
def upload_image(request, dir_name):
    ##################
    #  kindeditor图片上传返回数据格式说明:
    # {"error": 1, "message": "出错信息"}
    # {"error": 0, "url": "图片地址"}
    ##################
    result = {"error": 1, "message": "上传出错"}
    files = request.FILES.get("imgFile", None)
    if files:
        result =image_upload(files, dir_name)
    return HttpResponse(json.dumps(result), content_type="application/json")

#目录创建
def upload_generation_dir(dir_name):
    today = dt.datetime.today()
    dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
    if not os.path.exists(settings.MEDIA_ROOT):
        os.makedirs(settings.MEDIA_ROOT)
    return dir_name

# 图片上传
def image_upload(files, dir_name):
    #允许上传文件类型
    allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
    file_suffix = files.name.split(".")[-1]
    if file_suffix not in allow_suffix:
        return {"error": 1, "message": "图片格式不正确"}
    relative_path_file = upload_generation_dir(dir_name)
    path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
    if not os.path.exists(path): #如果目录不存在创建目录
        os.makedirs(path)
    file_name=str(uuid.uuid1())+"."+file_suffix
    path_file=os.path.join(path, file_name)
    file_url = settings.MEDIA_URL + relative_path_file + file_name
    open(path_file, 'wb').write(files.file.read())
    return {"error": 0, "url": file_url}

5.config.js 配置

该配置文件主要是对django admin后台作用的,比如说我们现在有一个news的app,我们需要对该模块下的 news类的content加上富文本编辑器,这里需要做两步

第一:在news 的admin.py中加入

class Media:
    js = (
        '/static/js/kindeditor-4.1.10/kindeditor-min.js',
        '/static/js/kindeditor-4.1.10/lang/zh_CN.js',
        '/static/js/kindeditor-4.1.10/config.js',
    )

第二:config.js 中配置
上边说了我们是要对news的content加上富文本编辑器,那么我们首先要定位到该文本框的name属性,鼠标右键查看源代码

  <textarea class="" cols=60 id=ie_new_content name=new_content rows=10 required>

config.js 中加入:

//news
KindEditor.ready(function(K) {
    K.create('textarea[name="new_content"]', {
        width : "800px",
        height : "500px",
        uploadJson: '/admin/uploads/kindeditor',
    });
});

这个例子写的太复杂了,直接在页面引用js,然后在javascript标签内初始化富文本就可以。

例子2

python+django常用富文本插件使用配置(ckeditor,kindeditor)

普通使用HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <textarea name="content" id="content"></textarea>
     
    <script src="/static/js/jquery-1.12.4.js"></script>
    <script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
    <script>
        $(function () {
            initKindEditor();
        });
     
        function initKindEditor() {
            var kind = KindEditor.create('#content', {
                width: '100%',       // 文本框宽度(可以百分比或像素)
                height: '300px',     // 文本框高度(只能像素)
                minWidth: 200,       // 最小宽度(数字)
                minHeight: 400      // 最小高度(数字)
            });
        }
    </script>

</body>
</html>

上传文件示例

kind.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form>
    {% csrf_token %}
    <div style="width: 500px;margin: 0 auto">
        <textarea id="content"></textarea>
    </div>
    <input type="submit" value="提交"/>
</form>

<script src="/static/js/jquery-1.12.4.js"></script>
<script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>

<script>
    $(function () {

        KindEditor.create('#content', {
            {#                items: ['superscript', 'clearhtml', 'quickformat', 'selectall']#}
            {#                noDisableItems: ["source", "fullscreen"],#}
            {#                designMode: false#}
            uploadJson: '/upload_img/',
            fileManagerJson: '/file_manager/',
            allowImageRemote: true,
            allowImageUpload: true,
            allowFileManager: true,
            extraFileUploadParams: {
                csrfmiddlewaretoken: "{{ csrf_token }}"
            },
            filePostName: 'fafafa'

        });


    })
</script>

</body>
</html>

后台代码

views.py
def kind(request):
    return render(request, 'kind.html')

def upload_img(request):
    request.GET.get('dir')
    print(request.FILES.get('fafafa'))
    # 获取文件保存
    import json
    dic = {                             #后台向前端返回的值
        'error': 0,                    #0表示的是正确的,1代表错误
        'url': '/static/image/图片.jpg',
        'message': '错误了...'
    }

    return HttpResponse(json.dumps(dic))

import os
import time
import json
def file_manager(request):    
    dic = {}
    root_path = 'E:/week_23_1/static'
    static_root_path = '/static/'
    request_path = request.GET.get('path')
    if request_path:
        abs_current_dir_path = os.path.join(root_path, request_path)
        move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
        dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path

    else:
        abs_current_dir_path = root_path
        dic['moveup_dir_path'] = ''     #  上一级目录

    dic['current_dir_path'] = request_path  #current_dir_path 指当前的路径
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []            #文件目录
    for item in os.listdir(abs_current_dir_path):         #listdir 就是把某一路径下的东西全部拿下来
        abs_item_path = os.path.join(abs_current_dir_path, item)
        a, exts = os.path.splitext(item)
        is_dir = os.path.isdir(abs_item_path)
        if is_dir:
            temp = {
                'is_dir': True,   #是否是dir
                'has_file': True, #目录下面是否存在文件
                'filesize': 0,   #文件大小是多少
                'dir_path': '',  #当前的路径是在哪
                'is_photo': False,  #是否是图片
                'filetype': '',    #文件的类型是什么
                'filename': item,  #文件名是什么
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) #文件创始时间是什么
            }
        else:
            temp = {
                'is_dir': False,
                'has_file': False,
                'filesize': os.stat(abs_item_path).st_size,
                'dir_path': '',
                'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
                'filetype': exts.lower().strip('.'),
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }

        file_list.append(temp)
    dic['file_list'] = file_list
    return HttpResponse(json.dumps(dic))

一个上传的python例子