Django自帶的Admin後臺,好用,TinyMCE做爲富文本編輯器,也蠻好用的,這二者結合起來在作博客的時候很方便(固然博客可能更適合用Markdown來寫),可是Django-TinyMCE這個組件默認沒有圖片上傳功能的,須要咱們本身實現,本文將一步步帶你們實現這個圖片上傳功能。html
讀者也能夠觸類旁通實現其餘須要和Django結合的功能。前端
在任一views.py
裏添加代碼:java
import os from django.conf import settings from django.http import JsonResponse from django.utils import timezone from django.views.decorators.csrf import csrf_exempt @csrf_exempt def upload_image(request): if request.method == "POST": file_obj = request.FILES['file'] file_name_suffix = file_obj.name.split(".")[-1] if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: return JsonResponse({"message": "錯誤的文件格式"}) upload_time = timezone.now() path = os.path.join( settings.MEDIA_ROOT, 'tinymce', str(upload_time.year), str(upload_time.month), str(upload_time.day) ) # 若是沒有這個路徑則建立 if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, file_obj.name) file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}' if os.path.exists(file_path): return JsonResponse({ "message": "文件已存在", 'location': file_url }) with open(file_path, 'wb+') as f: for chunk in file_obj.chunks(): f.write(chunk) return JsonResponse({ 'message': '上傳圖片成功', 'location': file_url }) return JsonResponse({'detail': "錯誤的請求"})
urlpatterns = [ # 上傳圖片 path('upload_image/', views.upload_image), # tinymce 編輯器 path('tinymce/', include('tinymce.urls')), ]
因爲tinymce是一個前端組件,因此須要使用js來配置。python
在static/tinymce/js
目錄下添加一個js文件(目錄不存在請手動建立),名字隨意,我這裏是textareas.js
:jquery
tinymce.init({ selector: 'textarea', // change this value according to your HTML images_upload_url: '/upload_image/', // Django路由中圖片上傳地址 height: 500, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], menubar: 'favs file edit view insert format tools table help', toolbar: 'undo redo | formatselect | ' + 'bold italic backcolor | alignleft aligncenter ' + 'alignright alignjustify | bullist numlist outdent indent | ' + 'code image | ' + 'removeformat | help', language: 'zh_CN', });
這段配置代碼裏面我加了一些插件,參照官方文檔改了一下菜單欄和工具欄,而且把顯示語言改爲中文(默認是英文)。linux
注意裏面的images_upload_url
,這個是剛纔配置了上傳圖片邏輯的路由。android
關於TinyMCE的配置能夠參考官方文檔:https://www.tiny.cloud/docs/demo/basic-example/django
最後,咱們須要在用到TinyMCE的admin中配置自定義的js,才能使前面的配置生效。c#
參考代碼以下,按照本身的實際model配置就好了。編輯器
@admin.register(models.Activity) class ActivityAdmin(admin.ModelAdmin): list_display = ['pk', 'title'] class Media: js = [ 'tinymce/jquery.tinymce.min.js', 'tinymce/tinymce.min.js', 'tinymce/js/textareas.js' ]
通過上面的配置就完成了,如今已經能夠了,打開admin後臺有tinymce字段的地方試一下唄~
效果OK~
我整理了一系列的技術文章和資料,在公衆號「程序設計實驗室」後臺回覆 linux、flutter、c#、netcore、android、kotlin、java、python 等可獲取相關技術文章和資料,同時有任何問題均可以在公衆號後臺留言~