Blog中有文章Model,文章内容会包括各种格式的数据,比如:图片、超链接、段落等。为了达到这个目的,我们可以使用富文本编辑器。
我们有多重选择来使用富文本编辑器,比如kindeditor、django-ckeditor、自定义ModelAdmin的媒体文件。
方案一:使用小巧灵活的kindeditor,步骤如下:
步骤1.1、从http://kindeditor.org/download下载kindeditor-4.1.11-en.zip,并将其解压到static下
步骤1.2:在kindeditor-4.1.11下增加文件config.js,
内容如下:
KindEditor.ready(function(K) { window.editor = K.create('textarea[name="content"]', { 'width':'800px', 'height':'500px' }); });
textarea[name="content"]是表示文章的content字段对应的html
步骤1.3:在admin.py增加ArticleAdmin
将kindeditor应用到Article上,我们可以ModelAdmin asset definitions。There are times where you would like add a bit of CSS and/or JavaScript to the add/change views. This can be accomplished by using a Media inner class on your ModelAdmin:
class ArticleAdmin(admin.ModelAdmin): class Media: js = ( '/static/kindeditor-4.1.11/kindeditor-all.js', '/static/kindeditor-4.1.11/lang/zh-CN.js', '/static/kindeditor-4.1.11/config.js', ) admin.site.register(Article, admin_class=ArticleAdmin)
这样就将kindeditor加上了富文本编辑器。
但是如果我们上次图片仍然会报错,因为我们并没有处理文件上传按钮。
步骤1.4:在config.js加入
'uploadJson':'/admin/upload/kindeditor',
这里/admin/upload/kindeditor是python的路由。
在url.py中有配置url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),
dir_name是文件的存储路径。
步骤1.5:upload_image是自定义的保存图片的函数。
from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt import os import uuid import json import datetime as dt @csrf_exempt def upload_image(request, dir_name): ################## # kindeditor图片上传返回数据格式说明: # {"error": 1, "message": "出错信息"} # {"error": 0, "url": "图片地址"} ################## result = {"error": 1, "message": "上传出错"} files = request.FILES.get("imgFile", None) if files: result = image_upload(files, dir_name) return HttpResponse(json.dumps(result), content_type="application/json") # 目录创建 def upload_generation_dir(dir_name): today = dt.datetime.today() url_part = dir_name + '/%d/%d/' % (today.year, today.month) dir_name = os.path.join(dir_name, str(today.year), str(today.month)) print("*********", os.path.join(settings.MEDIA_ROOT, dir_name)) if not os.path.exists(os.path.join(settings.MEDIA_ROOT, dir_name)): os.makedirs(os.path.join(settings.MEDIA_ROOT, dir_name)) return dir_name,url_part # 图片上传 def image_upload(files, dir_name): # 允许上传文件类型 allow_suffix = ['jpg', 'png', 'jpeg', 'gif', 'bmp'] file_suffix = files.name.split(".")[-1] if file_suffix not in allow_suffix: return {"error": 1, "message": "图片格式不正确"} relative_path_file, url_part = upload_generation_dir(dir_name) path = os.path.join(settings.MEDIA_ROOT, relative_path_file) print("&&&&path", path) if not os.path.exists(path): # 如果目录不存在创建目录 os.makedirs(path) file_name = str(uuid.uuid1()) + "." + file_suffix path_file = os.path.join(path, file_name) file_url =settings.MEDIA_URL + url_part +file_name open(path_file, 'wb').write(files.file.read()) return {"error": 0, "url": file_url}
文件保存后,路径为<img src="/upload/kindeditor/2017/3/b0b2c36e-0150-11e7-b520-f816544b9ec4.jpg" alt="" />
步骤1.6:使用django配置/upload来显示图片。
from django.views.static import serve
url(r'^upload/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
步骤1.7:setting增加media的配置
MEDIA_URL = "/upload/"
MEDIA_ROOT = os.path.join(BASE_DIR, "upload")
方案二:使用django-ckeditor参见https://github.com/django-ckeditor/django-ckeditor