django使用ckeditor上傳圖片


1、在模型類中設置字段為富文本類型,這里需要注意引入的是RichTextUploadingField,以允許上傳圖片,需要和RichTextField區分開

from ckeditor_uploader.fields import RichTextUploadingField
class
spit_model(models.Model): """模型類""" user = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='吐槽發布者') content = RichTextUploadingField(verbose_name='吐槽內容', max_length=200)

2、項目中ckeditor的安裝及配置

pip install django-ckeditor
INSTALLED_APPS = [
    ...
  'ckeditor', # 富文本編輯器   'ckeditor_uploader', # 富文本編輯器上傳圖片模塊 ... ]
# 富文本編輯器ckeditor配置 CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', # 工具條功能 'height': 300, # 編輯器高度 'width': 300, # 編輯器寬 }, }

 CKEDITOR_UPLOAD_PATH = ''  # 圖片ckeditor文件上傳路徑,這里使用七牛雲存儲,不填

2、html頁面中加入textarea標簽

<div>
<
textarea id="editor_id"></textarea>
</div>

3、頁面中引入控制html頁面的JS和ckeditor的JS文件, 在django的installed_app中注冊應用時,會自動在虛擬環境中生成應用信息/home/python/.virtualenvs/django_1.11.16_py3/lib/python3.5/site-packages/ckeditor/static/ckeditor/ckeditor/

在js路徑前加上域名,否則服務器會在live-server的默認端口下進行網絡通訊,查找js
<script type="text/javascript" src="js/spit-submit.js"></script>
<
script src="http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js"></script>

4、在vue變量的mounted方法中加入

let vm = new Vue({
  ...
    mounted:function () {
        CKEDITOR.replace('editor_id', { filebrowserUploadUrl:'http://127.0.0.1:8000/ckeditor/upload/' }); // 將id選擇器的文本域替換成為富文本,並手動設置文件上傳的請求路徑,默認請求路徑為live-server的路徑,必須設置為服務器的域名和端口
    },
});

5、后端設置總路由,'ckeditor_uploader.urls'中會將接收到的請求進行csrf校驗免除,並限制了只有登錄用戶才可以上傳圖片,ckeditor默認應用的是django-admin的用戶校驗方法,django-admin的校驗方法不允許跨域請求,我們需要使上傳圖片的類試圖函數繼承自django-restframework的APIVIew,

   # url(r'^ckeditor/', include('ckeditor_uploader.urls')),  # 為富文本編輯器添加總路由
    # url(r'^ckeditor/upload/', ImageUploadView.as_view()),  # 為富文本編輯器添加總路由
    # url(r'^ckeditor/upload/', csrf_exempt(ImageUploadView.as_view())),  # 為富文本編輯器添加總路由
    url(r'^ckeditor/', csrf_exempt(ImageUploadView.as_view())),  # 為富文本編輯器添加總路由

6、在應用中改寫路由和類視圖,使用permission_classes對請求權限進行限制

# 配置路由
urlpatterns = [
    url(r'^upload/$', ImageUploadView.as_view()),
]


from ckeditor_uploader import image_processing,utils
from django.conf import settings
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.utils.html import escape


class ImageUploadView(APIView):
    permission_classes = [IsAuthenticated]
    http_method_names = ['post']

    def post(self, request, **kwargs):
        """
        Uploads a file and send back its URL to CKEditor.
        """
        uploaded_file = request.FILES['upload']

        backend = image_processing.get_backend()

        ck_func_num = request.GET.get('CKEditorFuncNum')
        if ck_func_num:
            ck_func_num = escape(ck_func_num)

        # Throws an error when an non-image file are uploaded.
        if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
            try:
                backend.image_verify(uploaded_file)
            except utils.NotAnImageException:
                return HttpResponse("""
                    <script type='text/javascript'>
                    window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
                    </script>""".format(ck_func_num))

        saved_path = self._save_file(request, uploaded_file)
        if len(str(saved_path).split('.')) > 1:
            if(str(saved_path).split('.')[1].lower() != 'gif'):
                self._create_thumbnail_if_needed(backend, saved_path)
        url = utils.get_media_url(saved_path)

        if ck_func_num:
            # Respond with Javascript sending ckeditor upload url.
            return HttpResponse("""
            <script type='text/javascript'>
                window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
            </script>""".format(ck_func_num, url))
        else:
            retdata = {'url': url, 'uploaded': '1',
                       'fileName': uploaded_file.name}
            return JsonResponse(retdata)


免責聲明!

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



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