django框架加入simditor富文本编辑器,使用mako进行渲染
生活随笔
收集整理的這篇文章主要介紹了
django框架加入simditor富文本编辑器,使用mako进行渲染
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.安裝依賴
django-simditor==0.0.152.配置
INSTALLED_APPS += ('simditor', )SIMDITOR_TOOLBAR = ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale','color', '|', 'ol', 'ul', 'blockquote', 'table', '|', 'link', 'image','hr', '|', 'indent', 'outdent', 'alignment', # '|', 'markdown' ] SIMDITOR_UPLOAD_PATH = 'uploads/' SIMDITOR_IMAGE_BACKEND = 'pillow' # 圖片上傳的url SIMDITOR_CONFIGS = {'toolbar': SIMDITOR_TOOLBAR,'upload': {'url': SITE_URL + '/simditor/upload/','fileKey': 'upload','image_size': 1024 * 1024 * 4 # max image size 4MB},'emoji': {'imagePath': '/static/simditor/images/emoji/'} }3.生成simditor編輯器form的代碼
# -*- coding: utf-8 from __future__ import unicode_literals, absolute_import from django.conf.urls import include, url from simditor import utils, image_processing from .widgets import SimditorWidget import os from datetime import datetimefrom django.conf import settings from django.core.files.storage import default_storagefrom django.http import JsonResponsefrom django.views import generic from django.views.decorators.csrf import csrf_exempt# from . import utils, image_processingclass SimditorEditor():"""Editors should inherit from this. See wiki.editors for examples."""# The editor id can be used for conditional testing. If you write your# own editor class, you can use the same editor_id as some editoreditor_id = 'simditor'def get_admin_widget(self):return SimditorWidget()def get_widget(self, instance=None):return SimditorWidget()def get_urls(self):return [url(r'^simditor/', include('simditor.urls'))]class AdminMedia:css = {'all': ('wiki/simditor/styles/simditor.css','wiki/simditor/styles/simditor-markdown.css',)}js = ('wiki/simditor/scripts/jquery.min.js','wiki/simditor/scripts/module.js','wiki/simditor/scripts/uploader.js','wiki/simditor/scripts/hotkeys.js','wiki/simditor/scripts/simditor.js','wiki/simditor/scripts/marked.js','wiki/simditor/scripts/to-markdown.js','wiki/simditor/scripts/simditor-markdown.js',)class Media:css = {'all': ('wiki/simditor/styles/simditor.css','wiki/simditor/styles/simditor-markdown.css',)}js = ('wiki/simditor/scripts/jquery.min.js','wiki/simditor/scripts/module.js','wiki/simditor/scripts/uploader.js','wiki/simditor/scripts/hotkeys.js','wiki/simditor/scripts/simditor.js','wiki/simditor/scripts/marked.js','wiki/simditor/scripts/to-markdown.js','wiki/simditor/scripts/simditor-markdown.js',)def get_upload_filename(upload_name):# Generate date based path to put uploaded file.date_path = datetime.now().strftime('%Y/%m/%d')# Complete upload path (upload_path + date_path).upload_path = os.path.join(settings.SIMDITOR_UPLOAD_PATH, date_path)if getattr(settings, 'SIMDITOR_UPLOAD_SLUGIFY_FILENAME', True):upload_name = utils.slugify_filename(upload_name)return default_storage.get_available_name(os.path.join(upload_path, upload_name))def upload_handler(request):files = request.FILESupload_config = settings.SIMDITOR_CONFIGS.get('upload', {'fileKey': 'upload'})filekey = upload_config.get('fileKey', 'upload')uploaded_file = files.get(filekey)if not uploaded_file:retdata = {'file_path': '', 'success': False,'msg': '圖片上傳失敗,無法獲取到圖片對象!'}return JsonResponse(retdata)image_size = upload_config.get('image_size')if image_size and uploaded_file.size > image_size:retdata = {'file_path': '', 'success': False,'msg': '上傳失敗,已超出圖片最大限制!'}return JsonResponse(retdata)backend = image_processing.get_backend()if not getattr(settings, 'SIMDITOR_ALLOW_NONIMAGE_FILES', True):try:backend.image_verify(uploaded_file)except utils.NotAnImageException:retdata = {'file_path': '', 'success': False,'msg': '圖片格式錯誤!'}return JsonResponse(retdata)filename = get_upload_filename(uploaded_file.name)saved_path = default_storage.save(filename, uploaded_file)url = utils.get_media_url(saved_path)is_api = settings.SIMDITOR_CONFIGS.get('is_api', False)url = request.META.get('HTTP_ORIGIN') + url if is_api else urlretdata = {'file_path': url, 'success': True, 'msg': '上傳成功!'}return JsonResponse(retdata)class ImageUploadView(generic.View):"""ImageUploadView."""http_method_names = ['post']def post(self, request, **kwargs):"""Post."""return upload_handler(request)UPLOAD = csrf_exempt(ImageUploadView.as_view())這里有一個坑,由于SimditorWidget()從依賴中引入不識別,我解決的辦法:將這個內容所在的文件從依賴中拷貝出來,直接從這個文件引入
widgets.py
4.form表單部分代碼
forms.py文件 class CreateForm(forms.Form, SpamProtectionMixin):def __init__(self, request, urlpath_parent, *args, **kwargs):super(CreateForm, self).__init__(*args, **kwargs)# 富文本字段richtext = forms.CharField(label=_('Contents'),required=False,widget=SimditorEditor().get_widget())article.py文件 class Create(FormView, ArticleMixin):form_class = forms.CreateFormtemplate_name = "wiki/create.html"最后一個問題就是上傳圖片會出的問題:上傳需要url路由,不然上傳不識別路由報錯,導致上傳失敗
from django.views.decorators.csrf import csrf_exempt from .simditor import ImageUploadView # 從simditor.py導入的urlpatterns += [url(r'^simditor/upload', csrf_exempt(ImageUploadView.as_view())), ]這樣就可以識別了
效果:
總結
以上是生活随笔為你收集整理的django框架加入simditor富文本编辑器,使用mako进行渲染的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pmac联合QT开发入门指南
- 下一篇: KEBA控制器通过NT50连接西门子S7