1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 11. Django 引入富文本编辑器KindEditor

11. Django 引入富文本编辑器KindEditor

时间:2022-03-02 21:40:48

相关推荐

11. Django 引入富文本编辑器KindEditor

打开微信扫一扫,关注微信公众号【数据与算法联盟】

转载请注明出处:/gamer_gyt

博主微博:/234654758

Github:/thinkgamer

写在前边的话

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

KindEditor介绍

官网地址是:

目前最新版本是4.1.1,我现在做这个东西是用python3.5 ,django 1.10.4 ,三者之间完全兼容

看一张效果图吧:

使用过程

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:主要是对上传的图片做一些限制

# -*- coding: utf-8 -*-from django.http import HttpResponsefrom django.conf import settingsfrom django.views.decorators.csrf import csrf_exemptimport osimport uuidimport jsonimport datetime as dt@csrf_exemptdef 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_suffixpath_file=os.path.join(path, file_name)file_url = settings.MEDIA_URL + relative_path_file + file_nameopen(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 中加入:

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

至此,已经完成,如果你还有什么不懂的,可以加我关注我的微信公众号,进行提问,谢谢!

Over!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。