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

Blog中有文章Model,文章內容會包括各類格式的數據,好比:圖片、超連接、段落等。爲了達到這個目的,咱們能夠使用富文本編輯器。html

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

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

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

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

內容以下:json

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

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

步驟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:ide

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

相關文章
相關標籤/搜索