Web框架之Django【进阶篇】- KindEditor

与世无争的帅哥 提交于 2019-12-05 06:47:54

下载

1、进入官网

2、下载

3、文件夹说明

├── asp                          asp示例
├── asp.net                    asp.net示例
├── attached                  空文件夹,放置关联文件attached
├── examples                 HTML示例
├── jsp                          java示例
├── kindeditor-all-min.js 全部JS(压缩)
├── kindeditor-all.js        全部JS(未压缩)
├── kindeditor-min.js      仅KindEditor JS(压缩)
├── kindeditor.js            仅KindEditor JS(未压缩)
├── lang                        支持语言
├── license.txt               License
├── php                        PHP示例
├── plugins                    KindEditor内部使用的插件
└── themes                   KindEditor主题

基本使用

基本代码

<textarea name="content" id="content"></textarea>
 
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
    $(function () {
        initKindEditor();
    });
 
     // 第一个参数:#content ID选择器
    // 第二个参数:字典{}
    function initKindEditor() {
        var kind = KindEditor.create('#content', {    
            width: '100%',       // 文本框宽度(可以百分比或像素)
            height: '300px',     // 文本框高度(只能像素)
            minWidth: 200,       // 最小宽度(数字)
            minHeight: 400      // 最小高度(数字)
        });
    }
</script>

详细参数(官方中文文档)

     http://kindeditor.net/docs/option.html

上传文件示例

urls:

url(r'^kind/$', views.kind),
url(r'^upload_img/$', views.upload_img),
url(r'^file_manager/$', views.file_manager),

views:

####################KindEditor###############
def kind(request):
    return render(request, 'day24-app06/kind.html')

def upload_img(request):
    request.GET.get('dir')   # 根据js中参数uploadJson,获取上传的对象类型(图片,flash, 视音频...)

    print(request.FILES.get('fafafa'))

    # 获取文件保存,把文件路径返回给他即可
    import json
    dic = {
        'error': 0,
        'url': '/static/imgs/20130809170025.png',  # 内部用iframe+form实现的
        'message': '错误了...'
    }

    return HttpResponse(json.dumps(dic))

import os
import time
import json
# 成型代码:
# 知识点:os.listdir -->root_path
def file_manager(request):
    """
    文件管理
    :param request:
    :return:
    {
        moveup_dir_path: 上一级目录
        current_dir_path: 当前目录
        current_url: 文件url的前缀
        file_list: [
            {  第一个文件
                'is_dir': True,
                'has_file': True,
                'filesize': 0,
                'dir_path': '',
                'is_photo': False,
                'filetype': '',
                'filename': xxx.png,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            },
            {
                'is_dir': True,
                'has_file': True,
                'filesize': 0,
                'dir_path': '',
                'is_photo': False,
                'filetype': '',
                'filename': xxx.png,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }
        ]

    }


    """
    dic = {}
    root_path = 'C:/Users/Administrator/PycharmProjects/editors/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
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []
    for item in os.listdir(abs_current_dir_path):
        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,
                '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))

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div>
    <h1>文章内容</h1>
    {{ request.POST.content|safe }}
</div>
<form method="POST">
    <h1>请输入内容:</h1>
    {% csrf_token %}
    <div style="width: 500px; margin: 0 auto;">
        <textarea name="content" id="content"></textarea>
    </div>
    <input type="submit" value="提交"/>
</form>

<script src="/static/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
            designMode: false,

            filtermode: true, // 默认是true,过滤标签,js只能过滤一部分,不能真正的完全过滤

            resizeType: 1, // 改变编辑器的宽度

            syncType: false, // 默认true,false不允许用户提交数据(相当于把标签的name删除了,后台获取不到数据)

            // 上传都会用这个url (flash,视频,文件上传...)
            uploadJson: '/upload_img/', // 自定义上传提交的url,写个url的视图函数,get是不能发文件的,只有post提交可以发文件

            fileManagerJson: '/file_manager/', // 图片空间管理
            allowFileManager: true,  // 支持文件文件管理

            allowImageRemote: true,  // url: 图片链接
            allowImageUpload: true,  // 本地上传

            // 额外传个参数到后台,比如上传文件、视音频、flash对象受到csrf的限制,如何解决csrf限制?
            extraFileUploadParams: {
                // {% csrf_token %}是一个隐藏的input标签,name=csrfmiddlewaretoken
                csrfmiddlewaretoken: "{{ csrf_token }}" // 获取csrf随机字符串,并发给后台
            },
            filePostName: 'fafafa'  // 自定义上传对象的name,后台可直接get('fafafa')获取对象

        });
    })
</script>

<!-- 补充 -->
<script>
    $(function () {
        initKindEditor();
    });

    function initKindEditor() {
        var a = 'kind';
        var kind = KindEditor.create('#content', {
            width: '100%',       // 文本框宽度(可以百分比或像素)
            height: '300px',     // 文本框高度(只能像素)
            minWidth: 200,       // 最小宽度(数字)
            minHeight: 400,      // 最小高度(数字)
            uploadJson: '/kind/upload_img/',
            extraFileUploadParams: {
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            fileManagerJson: '/kind/file_manager/',
            allowPreviewEmoticons: true,
            allowImageUpload: true
        });
    }
</script>

</body>
</html>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!