1. 程式人生 > >Django 設定admin後臺的某一個model的欄位為富文字編輯器

Django 設定admin後臺的某一個model的欄位為富文字編輯器

Django 設定admin後臺的某一個model的欄位的型別為富文字編輯器,該富文字編輯器不但能夠上傳資料,還能夠上傳圖片,並能夠顯示圖片。
首先,在models.py中,建立一個models類,欄位的型別先設定成CharField

class Article(models.Model):
    content = models.CharField(max_length=255, verbose_name='文章內容')

現在的話,在admin後臺顯示的輸入框是這個樣子的
在這裡插入圖片描述

現在,將上面型別的框要換成富文字編輯器
首先,去網上下載http://kindeditor.net/down.php包
在這裡插入圖片描述

下載之後,是一個壓縮包,之後解壓是一個kindeditor資料夾。將這個資料夾複製到static資料夾下
在這裡插入圖片描述
之後將kindeditor資料夾下沒有必要的資料夾刪除,比如:asp、asp.net、jsp、php幾個資料夾刪除。
在這裡插入圖片描述

之後,由於文章新增需要使用富文字編輯器,所以在admin.py中,指定富文字編輯器要使用的一些css、js等檔案;

from django.contrib import admin
from .models import *


class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'desc', 'click_num', 'comment_num')

    # 設定admin後臺的文章Model列表頁,哪些欄位可以被點選。
    list_display_links = ('title', 'desc')

    # 設定哪些欄位是可以編輯的
    # list_editable = ('click_num', 'comment_num')

    # fields = () 設定新增文章時,顯示哪些欄位。

    # 由於文章新增需要使用富文字編輯器,所有在這裡,指定富文字編輯器要使用的一些css、js等檔案;
    class Media:
        js = (
            '/static/kindeditor/kindeditor-all-min.js',
            '/static/kindeditor/lang/zh-CN.js',
            '/static/kindeditor/config.js'
        )
admin.site.register(Article, ArticleAdmin)

在kindeditor的資料夾下建立一個js檔名為config.js,其中,#id_content就是之前的那個編輯框的id
width就是富文字編輯框的寬度
height就是富文字編輯框的高度
uploadJson就是上傳檔案所繫結的路由,該路由在urls.py中需繫結函式,在函式中寫上傳之後的程式碼

KindEditor.ready(function(K){
   window.editor = K.create('#id_content', {
       width: '700px',
       height: '300px',
       uploadJson: '/admin/upload/'
   });
});

在這裡插入圖片描述

在urls.py中:

path('/admin/upload/',upload_img),

其中,我設定了圖片的路徑
settings.py中:

MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR,'uploads')
# MEDIA_URL主要就是對映MEDIA_ROOT。將來展示圖片的時候,要使用這個鍵找到MEDIA_ROOT這個值。否則圖片可以上傳,但是無法載入圖片

在urls.py 中:

re_path(r'uploads/(.*)$',serve,{'document_root':settings.MEDIA_ROOT}),

現在:編輯框變成:
在這裡插入圖片描述

最後,要完成在富文字編輯器裡上傳圖片,並且能夠正常顯示

就要在views.py檔案中,實現upload_img函數了

import json, datetime, os
from django.db.models import Count
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage

from .models import *

# csrf_exempt: 該裝飾器是用於檢視函式,不適合通用檢視。主要就是取消某一個檢視函式的csrf認證;
# csrf_protect: 某一個檢視函式需要csrf認證;

"""
當專案90%都不需要csrf認證:
將 'django.middleware.csrf.CsrfViewMiddleware' 這個中介軟體註釋,需要認證的檢視函式單獨新增裝飾器csrf_protect;
當專案90%都需要csrf認證:
將 'django.middleware.csrf.CsrfViewMiddleware' 這個中介軟體解註釋,不需要認證的檢視函式單獨新增裝飾器csrf_exempt;
"""

from django.views.decorators.csrf import csrf_exempt, csrf_protect


@csrf_exempt
def upload_img(request):
    # 接收admin後臺的富文字編輯器上傳的圖片,將這個圖片儲存在專案下的uploads目錄下;
    result = {'error': 1, 'message': '上傳圖片失敗'}
    # 獲取富文字編輯器上傳的圖片
    file = request.FILES.get('imgFile', None)
    if file:
        # 將圖片檔案寫入到本地
        result = image_save(file)
    else:
        # 返回錯誤資訊
        result = {'error': 1, 'message': '請選擇圖片'}
    return HttpResponse(json.dumps(result), content_type='application/json')


def image_save(file):
    # 儲存圖片的函式
    # 定義允許上傳的圖片型別
    allow_img = ['jpg', 'jpeg', 'png', 'gif']
    file_img = file.name.split('.')[-1]
    if file_img not in allow_img:
        return {'error': 0, 'message': '圖片格式不支援'}
    # 在/uploads/下建立一個資料夾,儲存富文字上傳的圖片
    now_date = datetime.datetime.now()
    # 利用settings.MEDIA_ROOT和dir拼接圖片的上傳路徑
    dir = 'kindeditor' + '/%d/%d/' % (now_date.year, now_date.month)
    img_url = settings.MEDIA_ROOT + '/' + dir

    if not os.path.exists(img_url):
        os.makedirs(img_url)
    with open(img_url + file.name, 'wb') as f:
        f.write(file.file.read())
    # 在返回上傳圖片的url地址時,不能返回img_url這個上傳路徑,需要返回MEDIA_URL這個地址;通過MEDIA_URL對映到MEDIA_ROOT。
    file_url = settings.MEDIA_URL + dir + file.name
    return {'error': 0, 'url': file_url}

在這裡插入圖片描述