Kindeditor在Django中使用

Author Avatar
人不如故 7月 20, 2017
  • 在其它设备中阅读本文章

一路走来,DJango也用了挺久了,自己也做了一些基于Django的小项目,具体可看github,但是Django默认的admin后台编辑文本框实在是太丑了,而且单一,其实在很久之前就想写这篇文章了,但是由于种种原因拖延到了现在,终于下定了决心来写,现在时间是00:17。


官网地址是:[http://kindeditor.net][5]
目前最新版本是4.1.1,我现在做这个东西是用python3.5 ,django 1.10.4 ,三者之间完全兼容
看一张效果图吧:

http://kindeditor.net


1:下载该文件,解压至相应的js文件目录

例如我的目录是:
这里我删除了多余的文件,因为是python项目,其他的都用不到,所以选择删除,节省空间

2:settings.py和urls.py配置

在项目的settings.py 中设置MEDIA_ROOT 目录
eg:

#文件上传配置
MEDIA_ROOT = os.path.join(BASE_DIR,’uploads’)

项目的根urls.py 配置
eg:

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, }),

3:编写upload.py文件

该文件存放于项目的根目录同名文件夹下,eg:

upload.py:主要是对上传的图片做一些限制

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):





    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}

4: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属性,鼠标右键查看源代码,如下红线标示:
这里写图片描述

config.js 中加入:

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

坚持原创技术分享,您的支持将鼓励我继续创作!