Django之富文字編輯器kindeditor 及上傳,djangokindeditor

來源:互聯網
上載者:User

Django之富文字編輯器kindeditor 及上傳,djangokindeditor
1.什麼是富文字編輯器

百度百科(https://baike.baidu.com/item/%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8/10954999?fr=aladdin)

KindEditor 是一套開源的線上HTML編輯器,主要用於讓使用者在網站上獲得所見即所得 (WYSIWYG)編輯效果,開發人員可以用 KindEditor 把傳統的多行文本輸入框(textarea)替換為可視化的富文本輸入框。 KindEditor 使用 JavaScript 編寫,可以無縫地與 Java、.NET、PHP、ASP 等程式整合,比較適合在 CMS、商城、論壇、部落格、Wiki、電子郵件等互連網應用上使用。2.Django配置 2.1 配置static靜態資源KindEditor是用JavaScript編寫的,這屬於static files,因此需要為Django設定static路徑。 首先在工程目錄下建立static檔案夾,這裡要注意的是千萬不要在my_app/下建立static檔案夾作為static檔案存放的目錄, 這會導致Django無法搜尋到自己的static 檔案。建立後好,在settings中配置static檔案目錄。添加以下代碼
STATIC_URL = '/static/'STATICFILES_DIRS = (    os.path.join(BASE_DIR,  'static'),)MEDIA_URL = '/uploads/'MEDIA_ROOT = os.path.join(BASE_DIR,  'uploads')

2.2 下載 

http://kindeditor.net/down.php

2.3 解壓並複製到項目目錄下

2.4 定義Media類並編輯kindeditor配置

class ArticleAdmin(admin.ModelAdmin):list_display = ('title', 'desc','click_count','date_publish')#顯示列list_display_links = ('title', 'desc',)#顯示列上的連結效果list_editable = ('click_count',)#可編輯的列fieldsets = ((None, {'fields': ('title', 'desc', 'content', 'user', 'category', 'tag',)}),('進階設定', {'classes': ('collapse',),#摺疊狀態'fields': ('click_count', 'is_recommend',)}),)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

KindEditor.ready(function (K) {    K.create('textarea[name=content]', {/*css元素*/        width: '800px',        height: '200px',        uploadJson: '/admin/upload/kindeditor',/*請求url*/    });});

2.5 配置url

urlpatterns = [url(r'^admin/', admin.site.urls),url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload.upload_image, name='upload_image'),]

upload.py

# -*- coding: utf-8 -*-from django.http import HttpResponsefrom django.conf import settingsfrom django.views.decorators.csrf import csrf_exemptimport osimport uuidimport jsonimport datetime as dt@csrf_exemptdef 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 + 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']    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}

3.測試

 

4.參考

http://kindeditor.net/docs/usage.html

http://kindeditor.net/docs/upload.html

https://docs.djangoproject.com/en/1.8/howto/static-files/

https://docs.djangoproject.com/en/1.8/topics/forms/media/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.