Blog_Django(四):Django使用Blog的富文本編輯器,文件上傳


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

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

方案一:使用小巧靈活的kindeditor,步驟如下:

步驟1.1、從http://kindeditor.org/download下載kindeditor-4.1.11-en.zip,並將其解壓到static下

步驟1.2:在kindeditor-4.1.11下增加文件config.js,

內容如下:

KindEditor.ready(function(K) {
    window.editor = K.create('textarea[name="content"]',
        {
            'width':'800px',
            'height':'500px'
        });
});

textarea[name="content"]是表示文章的content字段對應的html

步驟1.3:在admin.py增加ArticleAdmin

將kindeditor應用到Article上,我們可以ModelAdmin asset definitions。There are times where you would like add a bit of CSS and/or JavaScript to the add/change views. This can be accomplished by using a Media inner class on your ModelAdmin:

class ArticleAdmin(admin.ModelAdmin):
    class Media:
        js = (
            '/static/kindeditor-4.1.11/kindeditor-all.js',
            '/static/kindeditor-4.1.11/lang/zh-CN.js',
            '/static/kindeditor-4.1.11/config.js',
        )


admin.site.register(Article, admin_class=ArticleAdmin)

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

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

步驟1.4:在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是文件的存儲路徑。

步驟1.5: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}
upload.py

文件保存后,路徑為<img src="/upload/kindeditor/2017/3/b0b2c36e-0150-11e7-b520-f816544b9ec4.jpg" alt="" />

步驟1.6:使用django配置/upload來顯示圖片。

from django.views.static import serve

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

步驟1.7:setting增加media的配置

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

 

方案二:使用django-ckeditor參見https://github.com/django-ckeditor/django-ckeditor

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM