1. 程式人生 > >Django中富文字編輯器KindEditor的使用和圖片上傳

Django中富文字編輯器KindEditor的使用和圖片上傳

Blog中有文章Model,文章內容會包括各種格式的資料,比如:圖片、超連結、段落等。為了達到這個目的,我們可以使用富文字編輯器。

我們有多重選擇來使用富文字編輯器,比如kindeditor、django-ckeditor、自定義ModelAdmin的媒體檔案。

這樣就將kindeditor加上了富文字編輯器。

4.圖片上傳

但是如果我們上次圖片仍然會報錯,因為我們並沒有處理檔案上傳按鈕。

4.1:在config.js加入

'uploadJson':'/admin/upload/kindeditor',

這裡/admin/upload/kindeditor是python的路由。

在url.py中有配置url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),

dir_name是檔案的儲存路徑。

4.2:upload_image是自定義的儲存圖片的函式。

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() url_part = dir_name + '/%d/%d/' % (today.year, today.month) dir_name = os.path.join(dir_name, str(today.year), str(today.month)) print("*********", os.path.join(settings.MEDIA_ROOT, dir_name)) if not os.path.exists(os.path.join(settings.MEDIA_ROOT, dir_name)): os.makedirs(os.path.join(settings.MEDIA_ROOT, dir_name)) return dir_name,url_part # 圖片上傳 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, url_part = upload_generation_dir(dir_name) path = os.path.join(settings.MEDIA_ROOT, relative_path_file) print("&&&&path", path) 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 + url_part +file_name open(path_file, 'wb').write(files.file.read()) return {"error": 0, "url": file_url}

檔案儲存後,路徑為<img src="/upload/kindeditor/2018/5/dea7fffe-6251-11e8-946f-40b034409066.jpg" alt="" />

4.3:使用django配置/upload來顯示圖片。

from django.views.static import serve

url(r'^upload/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),

4.4:setting增加media的配置

MEDIA_URL = "/upload/"
MEDIA_ROOT = os.path.join(BASE_DIR, "upload")