python+django常用富文本插件使用配置(ckeditor,kindeditor)


KindEditor安裝配置

WEB開發離不開富文本編輯器,KindEditor和CKEditor是兩款不錯的第三方插件。

1.kindeditor下載

http://kindeditor.net/down.php

2.目錄結構(刪除多余的文件)

3.settings.py和urls.py配置
  在settings.py 中設置MEDIA_ROOT 目錄

 #文件上傳配置

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

 # urls.py 配置

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

4.upload.py 文件

  該文件存放在根目錄同名文件夾下

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

5.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屬性,鼠標右鍵查看源代碼

  <textarea class="" cols=60 id=ie_new_content name=new_content rows=10 required>

config.js 中加入:

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

這個例子寫的太復雜了,直接在頁面引用js,然后在javascript標簽內初始化富文本就可以。

例子2

普通使用HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <textarea name="content" id="content"></textarea>
     
    <script src="/static/js/jquery-1.12.4.js"></script>
    <script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
    <script>
        $(function () {
            initKindEditor();
        });
     
        function initKindEditor() {
            var kind = KindEditor.create('#content', {
                width: '100%',       // 文本框寬度(可以百分比或像素)
                height: '300px',     // 文本框高度(只能像素)
                minWidth: 200,       // 最小寬度(數字)
                minHeight: 400      // 最小高度(數字)
            });
        }
    </script>

</body>
</html>

上傳文件示例

kind.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form>
    {% csrf_token %}
    <div style="width: 500px;margin: 0 auto">
        <textarea id="content"></textarea>
    </div>
    <input type="submit" value="提交"/>
</form>

<script src="/static/js/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: false#}
            uploadJson: '/upload_img/',
            fileManagerJson: '/file_manager/',
            allowImageRemote: true,
            allowImageUpload: true,
            allowFileManager: true,
            extraFileUploadParams: {
                csrfmiddlewaretoken: "{{ csrf_token }}"
            },
            filePostName: 'fafafa'

        });


    })
</script>

</body>
</html>

后台代碼

views.py
def kind(request):
    return render(request, 'kind.html')

def upload_img(request):
    request.GET.get('dir')
    print(request.FILES.get('fafafa'))
    # 獲取文件保存
    import json
    dic = {                             #后台向前端返回的值
        'error': 0,                    #0表示的是正確的,1代表錯誤
        'url': '/static/image/圖片.jpg',
        'message': '錯誤了...'
    }

    return HttpResponse(json.dumps(dic))

import os
import time
import json
def file_manager(request):    
    dic = {}
    root_path = 'E:/week_23_1/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  #current_dir_path 指當前的路徑
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []            #文件目錄
    for item in os.listdir(abs_current_dir_path):         #listdir 就是把某一路徑下的東西全部拿下來
        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,   #是否是dir
                '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))
一個上傳的python例子

效果如下

 CKEditor使用配置

目前我用的是CKEditor

1.下載django-ckeditor包

https://pypi.org/project/django-ckeditor/

2.安裝插件包,這個是為了和django的model深度融合,不安裝只是前端配置使用應該也可以

pip install django-ckeditor 

3.settings.py 配置

INSTALLED_APPS = [
'ckeditor',                # 富文本編輯器
'ckeditor_uploader',
]
文件最下面加上
CKEDITOR_UPLOAD_PATH = 'ckeditor/'

4.在前端頁面創建富文本框

 //在頁面加入js文件

<script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>
//加入html代碼
<textarea type="text" id="id_content" cols="50" name="content" autocomplete="off"></textarea>
//創建CKEDITOR富文本框

function createCkeditor(name) {
var editor = CKEDITOR.instances[name];

if (editor) {
editor.destroy(true); //如果已經有一個實例,先銷毀再創建一個。這里name必須傳textarea的id。
//CKEDITOR.remove(editor);
}
CKEDITOR.replace(name, {
language: 'zh-cn',
skin: 'moono-lisa',
toolbar: 'Basic',
toolbarCanCollapse: true, //是否可以收縮工具欄
toolbarStartupExpanded: false, //工具欄是否默認展開
allowedContent: true,
removePlugins: 'elementspath',
resize_enabled: false,
width: '800px',
height: '300px',
baseFloatZIndex: '20000000',
});
}

//結合layui的layer彈出層使用,
function openAddSupervise() {
mainIndex = layer.open({
type: 1,
offset: 't',
title: '添加督察督辦',
content: $("#saveOrUpdateDiv"),
area: ['1000px', '500px'],
// btn:['保存','放棄'], 因為不能提交激發驗證,所以這里不適用btn,而是在content中定義提交表單按鈕
/* yes:function(index, layero) {
layer.msg(index);
},
btn2:function(index,layero){
layer.msg(index);
},
*/
success: function (index) {
//清空表單數據
$("#dataFrm")[0].reset(); //dom=>js obj[0],js=>dom $()
url = '{% url "adm:public-supervise-create" %}';
createCkeditor('id_content'); //必須傳id 彈出時創建調用上面函數富文本
}
});

5.通過ajax提交富文本內容

  ## 富文本的本質是用自身替代了html中的textarea,進行了站位,所以直接從textarea取值不行。

    等從后台拿到數據,回寫的時候,插件會自動把值賦給textarea

var content = CKEDITOR.instances.id_content.getData();   //拿到富文本框實例的內容
document.getElementById("id_content").value = content; //設置到html 表單中的textarea中去,再下一句跟隨表單提交
var params = $.param({"department": transferList}, true) + "&" + $.param({"filelist": filelist}, true) + "&" + $("#dataFrm").serialize();
//alert(params);
$.ajax({
type: "POST",
url: url,
data: params,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM