django整合ueditor富文字編輯器並解決圖片視頻等無法上傳顯示問題

來源:互聯網
上載者:User

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進行不同的操作

 
  1. def save_upload_file(PostFile,FilePath,action):

  2. if action == 'uploadfile':
  3. FilePathWrite = FilePath+'/'+str(PostFile)
  4. elif action == 'uploadimage':
  5. FilePathWrite = FilePath+'/'+str(PostFile)
  6. #elif action == 'uploadvideo':
  7. # FilePathWrite = videofile(FilePath,'/video/')
  8. else:
  9. FilePathWrite = FilePath

  10. try:
  11. f = open(FilePathWrite, 'wb')
  12. for chunk in PostFile.chunks():
  13. f.write(chunk)
  14. except Exception as E:
  15. f.close()
  16. return u"寫入檔案錯誤:"+ E.message
  17. f.close()
  18. return u"SUCCESS"
ok改完了發現,是可以上傳了,對應的檔案夾中也有上傳圖片,但是在對話方塊中卻無法顯示圖片,對應的路徑是錯誤的,這時候要修改另一個函數

還是修改DjangoUeditor.views 檔案 ,大約在258行,需要重新拼接下返回的圖片路徑,重新修改return_info 字典,修改為這樣,還是通過上傳操作重新定義返回的url


 
  1. import urllib
  2. if action == 'uploadvideo':
  3. url = urllib.basejoin(USettings.gSettings.MEDIA_URL, OutputPathFormat)
  4. else:
  5. url = urllib.basejoin(USettings.gSettings.MEDIA_URL, OutputPathFormat) + '/' + upload_file_name

  6. return_info = {
  7. 'url': url, # 儲存後的檔案名稱
  8. 'original': upload_file_name, # 原始檔案名
  9. 'type': upload_original_ext,
  10. 'state': state, # 上傳狀態,成功時返回SUCCESS,其他任何值將原樣返回至圖片上傳框中
  11. 'size': upload_file_size
  12. }

這下子就ok了,能夠上傳圖片,視頻,檔案了,也能基本使用了。不過還有一些比如塗鴉什麼的那些由於也用不到,咱未研究。


ok可以使用。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.