• Django中富文本编辑器KindEditor的使用和图片上传


    1.简介

    KindEditor 是一套开源的在线HTML编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用 KindEditor 把传统的多行文本输入框(textarea)替换为可视化的富文本输入框。 KindEditor 使用 JavaScript 编写,可以无缝地与 Java、.NET、PHP、ASP 等程序集成,比较适合在 CMS、商城、论坛、博客、Wiki、电子邮件等互联网应用上使用

    2.主要特点

    • 快速:体积小,加载速度快
    • 开源:开放源代码,高水平,高品质
    • 底层:内置自定义 DOM 类库,精确操作 DOM
    • 扩展:基于插件的设计,所有功能都是插件,可根据需求增减功能
    • 风格:修改编辑器风格非常容易,只需修改一个 CSS 文件
    • 兼容:支持大部分主流浏览器,比如 IE、Firefox、Safari、Chrome、Opera 

    3.使用

    3.1下载路径: http://kindeditor.net/down.php

    下载后根据需求删除以下目录。

    • asp - ASP程序
    • asp.net - ASP.NET程序
    • php - PHP程序
    • jsp - JSP程序
    • examples - 演示文件

    3.2将文件夹拷贝到项目根目录的/static/文件夹中:


    3.3在kineeditor目录下创建conifg.js配置文件

    #config.js
    KindEditor.ready(function(K) {
            // K.create('textarea[name=content]', {
            K.create('#id_content', {
                 '800px',
                height: '500px',
            });
    });

    注释: 这里的#id_content,或是name=content,是通过登录admin后,右击对应控件,选择审查元素获得的。

     3.4在admin.py对应的管理类中添加class Media,引入js文件。

    from .models import  Article
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ['title']
        class Media:
            js = ('/static/js/kindeditor-4.1.10/kindeditor-all-min.js',
                  '/static/js/kindeditor-4.1.10/lang/zh-CN.js',
                  '/static/js/kindeditor-4.1.10/config.js')
    
    admin.site.register(Article,ArticleAdmin)

    Blog中有文章Model,文章内容会包括各种格式的数据,比如:图片、超链接、段落等。为了达到这个目的,我们可以使用富文本编辑器。

    我们有多重选择来使用富文本编辑器,比如kindeditor、django-ckeditor、自定义ModelAdmin的媒体文件。

    这样就将kindeditor加上了富文本编辑器。

    4.图片上传

    但是如果我们上次图片仍然会报错,因为我们并没有处理文件上传按钮。

    4.1:在config.js加入

    'uploadJson':'/admin/upload/kindeditor',

    这里/admin/upload/kindeditor是python的路由。

    在url.py中有配置url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),

    dir_name是文件的存储路径。

    4.2:upload_image是自定义的保存图片的函数。

    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()
        url_part = dir_name + '/%d/%d/' % (today.year, today.month)
        dir_name = os.path.join(dir_name, str(today.year), str(today.month))
        print("*********", os.path.join(settings.MEDIA_ROOT, dir_name))
        if not os.path.exists(os.path.join(settings.MEDIA_ROOT, dir_name)):
            os.makedirs(os.path.join(settings.MEDIA_ROOT, dir_name))
        return dir_name,url_part
    
    
    # 图片上传
    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, url_part = upload_generation_dir(dir_name)
        path = os.path.join(settings.MEDIA_ROOT, relative_path_file)
        print("&&&&path", path)
        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 + url_part +file_name
        open(path_file, 'wb').write(files.file.read())
        return {"error": 0, "url": file_url}

    文件保存后,路径为<img src="/upload/kindeditor/2018/5/dea7fffe-6251-11e8-946f-40b034409066.jpg" alt="" />

    4.3:使用django配置/upload来显示图片。

    from django.views.static import serve

    url(r'^upload/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),

    4.4:setting增加media的配置

    MEDIA_URL = "/upload/"
    MEDIA_ROOT = os.path.join(BASE_DIR, "upload")


    参考文章
    http://www.cnblogs.com/wupeiqi/articles/6307554.html

    https://www.cnblogs.com/yangshl/p/6505308.html

  • 相关阅读:
    Maven仓库是什么
    Maven的工程类型有哪些?
    什么是Maven?
    MyBatis 与 Hibernate 有哪些不同?
    MySQL里有2000w数据,redis中只存20w的数据,如何保证redis中的数据都是热点数据?
    使用过Redis做异步队列么,你是怎么用的?
    我们怎样才能在动作类中获得Servlet API请求,响应,HttpSession等对象?
    forward 和redirect的区别 ?
    你所知道的微服务技术栈有哪些?请列举一二
    SpringMVC流程?
  • 原文地址:https://www.cnblogs.com/fungitive/p/9136122.html
Copyright © 2020-2023  润新知