django整合ueditor富文字編輯器並解決圖片視頻等無法上傳顯示問題
一般django背景文字編輯器比較簡單,所以增加ueditor編輯器。
ueditor編輯是百度開發開源產品,官網沒django版本。
django版本 https://github.com/zhangfisher/DjangoUeditor/archive/master.zip
解壓後將 DjangoUeditor 檔案夾複製到django項目目錄下,跟app目錄同級
開始修改 :
url.py檔案
匯入 fromDjangoUeditorimporturlsasDjangoUeditor_urls
增加路由 url(r'^ueditor/', include(DjangoUeditor_urls))
models 檔案
匯入 fromDjangoUeditor.models import UEditorField
對於需要使用編輯器的子段定義
context = UEditorField('內容',height=300, width=1000, default='', blank=True, imagePath="news", toolbars='full', filePath='files')
其中定義了文字框的大小和欄位預設值,imagePath 和filePath 定義圖片,視頻和檔案上傳的路徑 (相對於 settings.MEDIA_ROOT)
toolbars 定義功能的顯示複雜度 一般有 mini,besttome,nomal,full 等選項,具體在DjangoUeditor.settings中設定
這樣就初步可以使用了
但是圖片和視頻等上傳還是不行,上傳失敗,原因是因為上傳圖片時open的是個路徑,當傳視頻就可以了
這個就需要修改檔案DjangoUeditor.views 檔案 修改函數save_upload_file 大概在38行左右
直接修改成這樣,根據上傳的action進行不同的操作
- def save_upload_file(PostFile,FilePath,action):
- if action == 'uploadfile':
- FilePathWrite = FilePath+'/'+str(PostFile)
- elif action == 'uploadimage':
- FilePathWrite = FilePath+'/'+str(PostFile)
- #elif action == 'uploadvideo':
- # FilePathWrite = videofile(FilePath,'/video/')
- else:
- FilePathWrite = FilePath
- try:
- f = open(FilePathWrite, 'wb')
- for chunk in PostFile.chunks():
- f.write(chunk)
- except Exception as E:
- f.close()
- return u"寫入檔案錯誤:"+ E.message
- f.close()
- return u"SUCCESS"
ok改完了發現,是可以上傳了,對應的檔案夾中也有上傳圖片,但是在對話方塊中卻無法顯示圖片,對應的路徑是錯誤的,這時候要修改另一個函數
還是修改DjangoUeditor.views 檔案 ,大約在258行,需要重新拼接下返回的圖片路徑,重新修改return_info 字典,修改為這樣,還是通過上傳操作重新定義返回的url
- import urllib
- if action == 'uploadvideo':
- url = urllib.basejoin(USettings.gSettings.MEDIA_URL, OutputPathFormat)
- else:
- url = urllib.basejoin(USettings.gSettings.MEDIA_URL, OutputPathFormat) + '/' + upload_file_name
- return_info = {
- 'url': url, # 儲存後的檔案名稱
- 'original': upload_file_name, # 原始檔案名
- 'type': upload_original_ext,
- 'state': state, # 上傳狀態,成功時返回SUCCESS,其他任何值將原樣返回至圖片上傳框中
- 'size': upload_file_size
- }
這下子就ok了,能夠上傳圖片,視頻,檔案了,也能基本使用了。不過還有一些比如塗鴉什麼的那些由於也用不到,咱未研究。
ok可以使用。