Django中的富文本编辑器KindEditor使用

环境:python3.6.4、KindEditor  4.1.11、Django 2.0.6

首先下载KindEditor,官网 http://kindeditor.net/,目前看已经很少有更新了,不过主要是通过JS实现,目前看影响不大。

默认情况下KindEditor是没有直接用于Django的插件,所以需要我们简单的进行配置;

1.将解压后的文件,放到项目目录/static/js下(asp/asp.net/jsp/php都是对应语言的支持框架,对python执行无影响,可以直接删除):


2.在settings配置好static的配置,参照django官网:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),

3.在/static/js/kindeditor/目录下增加config.js代码,textarea指的是html中元素的name,也是就你希望富文本编辑器作用于哪个元素上:

KindEditor.ready(function (K) {
    K.create('textarea',{
        width:500,
        height:200,
    })
    
});

4.python代码中配置js的调用,当前以admin后台中的作用于TextField字段为例,在admin.py的模块Admin中填写一下内容:

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

那么截止当前富文本编辑器效果就已经出来了,不过默认图片上传功能对python没有实现,需要我们继续增加一些逻辑代码

1.在项目app目录下面添加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 #csrf_exempt装饰器是指避免csrf检查,由于富文本是表单提交,kindEditor没有对python支持,所以这一块csrf校验的话会出现错误
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 + dir_name):
        os.makedirs(settings.MEDIA_ROOT + dir_name)
    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}

2.media路径的一些设置:

settings.py

MEDIA_URL = '/uploads/'

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

urls.py

urlpatterns = [
    re_path('^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),
    re_path("^uploads/(?P<path>.*)$", serve,
                      {"document_root": settings.MEDIA_ROOT, }),
]

上面提到/static/js/kindeditor/目录下增加config.js代码中再增加一些配置,至此已经可以上传了

KindEditor.ready(function(K) {
                K.create('textarea[name=content]',{
                    width:'800px',
                    height:'200px',
                    uploadJson: '/admin/upload/kindeditor',
                });
        });

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值