django使用ckeditor上傳圖片
阿新 • • 發佈:2018-12-17
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)