由於django后台管理沒有富文本編輯器,看着好丑,展示出來的頁面不美觀,無法做到所見即所得的編輯方式,所以我們需要引入第三方富文本編輯器。
之前找了好多文檔已經博客才把這個功能做出來,有些博客雖然寫的很好,但是畢竟不是自己寫的好多地方要么不夠全面,要么看不懂,整理了一些大神的
博客,所以這次自己實現就決定寫這篇博客記錄下,以后如果有需求就不用到處找資料了,同時也分享給大家看看,提供借鑒。這次我使用的是kindeditor 富
文本編輯器。之所以選擇這個編輯器主要看是它功能齊全還美觀。下面這張圖是kindeditor的樣子,沒錯功能就是這么多,外觀就是這么好看。
好了開始我們的django 使用kindeditor之路。
在應用中使用
第一步:
到官網下載 kindeditor
下載好后刪除這些沒有的文件asp,asp.net,jsp,php.在django中這些都沒用。
第二步:將刪除后的文件引入自己的項目中。根目錄下的static/js/editor/
第三步,將kindeditor 的js文件引入到要做富文本編輯器的網頁中,

<script src="/static/js/editor/kindeditor/kindeditor-all-min.js"></script> <script src="/static/js/editor/kindeditor/lang/zh-CN.js"></script> <script src="/static/js/editor/kindeditor/themes/default/default.css"></script> <script> KindEditor.ready(function (k) { window.editor = k.create('#editor_id',{ resizeType:1, allowPreviewEmoticons : false, allowImageRemote : false, {#處理url#} uploadJson : '/upload/kindeditor', }); }) </script>
我項目中引入截圖,uploadJson 是上傳文件的url地址,這個要根據自己url是怎么配置具體更改。下面會講到url配置。
第四步,在thml的textarea 中加入一個id=editor_id ,這個就是富文本編輯框。這個id在上一步的js中有用到,這個需要注意下。

<textarea id="editor_id" name="content" style="height: 400px" >{{ text }}</textarea>
做到這一步富文本編輯框已經出來了,下面看是做django中的配置。
django中配置
第一步:配置靜態文件上傳目錄,編輯器中上傳的文件將保存在這里。

MEDIA_URL = '/static/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static/media")
第二步:在項目的urls配置文件中配置
第三步:在自己的應用中創建一個文件名為uploads.py 的模塊,
這里是在我的blog應用中,創建好后將下面這段代碼復制到文件中

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 + 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', 'zip', "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb", "doc", "docx", "xls", "xlsx", "ppt", "htm", "html", "txt", "zip", "rar", "gz", "bz2"] 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}
第四步:配置應用中的url
在應用的urls.py中導入剛才寫的視圖文件uploads.py
from blog.uploads import upload_image
url(r'^upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),

from blog.uploads import upload_image urlpatterns = [ url(r'^upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'), ]
上面這些步驟富文本編輯器應該可以正常使用了,包括上傳圖片,視頻。
下面我們來看下在admin后台管理中使用
首先在我們之前下載的kindeditor 目錄下新建一個config.js文件寫入這段代碼跟之前在應用中使用的是一樣的
KindEditor.ready(function (k) { window.editor = k.create('#id_text',{ #這個地方需要注意;模型類中使用 text = models.TextField()的話id就是id_text。如果是提前字段類型可以到瀏覽器中檢查,獲取到需要使用富文本編輯器的元素的id resizeType:1, allowPreviewEmoticons : false, allowImageRemote : false, uploadJson : '/upload/kindeditor', #這個是上傳圖片后台處理的url width:'800px', height:'400px', }); })

KindEditor.ready(function (k) { window.editor = k.create('#id_text',{ resizeType:1, allowPreviewEmoticons : false, allowImageRemote : false, uploadJson : '/upload/kindeditor', width:'800px', height:'400px', }); })
建議將settings.py 中間件中的csrf注釋掉,要不有可能post請求會報錯,其實這個功能沒太大用處。
接下來就需要去admin.py中注冊模型類。將其kindeditor的js文件引入到admin中
導入模型類,這里我的模型類是Post ,這個按照自己的模型類修改就可以了。原來的# admin.site.register(Post) 這樣的注冊方法直接注釋掉,

from django.contrib import admin from .models import * # Register your models here. # admin.site.register(Post) @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title'] class Media: # 在管理后台的HTML文件中加入js文件, 每一個路徑都會追加STATIC_URL/ js = ( '/static/js/editor/kindeditor/kindeditor-all-min.js', '/static/js/editor/kindeditor/zh_CN.js', '/static/js/editor/kindeditor/config.js', )
我的 模型類是這樣的,富文本編輯器是用在text 這個字段上。
由於每個人寫的代碼可能不一樣,所以有些地方並不完全通用,所以得自己琢磨着修改。第一次使用kinddetior,也是費了好大勁,翻閱了無數博客,拼拼湊湊出來的