Django 常用的富文本编辑器有ckeditor,ueditor,kindeditor,tinyme等.

  1. 在static目录下新建kindeditor目录.
  2. 下载kindeitor,http://kindeditor.googlecode.com/files/kindeditor-4.1.1.zip ,解压文件到kindeditor目录下.
  3. 在kindeditor目录下新建config.js.

config.js

1
2
3
4
5
6
7
8
9
KindEditor.ready(function(K) {
window.editor = K.create('#id_content',{
uploadJson: '/admin/upload/kindeditor',
// 指定大小
width:'800px',
height:'200px'
});
});

Django代码如下:

  • settings.py
1
2
3
4
5
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
# STATIC_ROOT='/home/xxoo/PycharmProjects/blogtest/static/admin'
MEDIA_URL="/upload/"
MEDIA_ROOT=os.path.join(BASE_DIR,'media/') #.replace('\\','/')
  • admin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from blog.models import blog
@admin.register(blog)
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title',)
class Media:
# 在管理后台的HTML文件中加入js文件, 每一个路径都会追加STATIC_URL/
js = (
'jquery.min.js',
'kindeditor/kindeditor-all.js',
'kindeditor/lang/zh-CN.js',
'kindeditor/config.js',
)
css = {
'all': ('kindeditor/themes/default/default.css','kindeditor/plugins/code/prettify.css')
}
  • models.py
1
2
3
4
5
6
7
8
9
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
class blog(models.Model): #博客
title = models.CharField(max_length=50) #标题
content = models.TextField() #内容,,,,id_content
date_time = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
  • views.py(图片上传)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# coding=utf-8
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse,Http404
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import os
import uuid
import json
import datetime as dt
def index(request):
return HttpResponse(123)
@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()
dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
if not os.path.exists(settings.MEDIA_ROOT + '/' + dir_name):
os.makedirs(settings.MEDIA_ROOT + '/' + dir_name)
return dir_name
# 图片上传
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 = upload_generation_dir(dir_name)
path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
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 + relative_path_file + file_name
open(path_file, 'wb').write(files.file.read()) # 保存图片
return {"error": 0, "url": file_url}
  • urls.py
1
2
3
4
5
6
7
8
9
10
11
from django.conf.urls import url
from django.contrib import admin
from blog import views
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^admin/upload/(?P<dir_name>[^/]+)$',views.upload_image, name='upload_image'),
url(r"^upload/(?P<path>.*)$", "django.views.static.serve", {"document_root": settings.MEDIA_ROOT,}),
]

执行python manage.py collectstatic,将所有静态文件复制到static admin目录下,修改admin/css/base.css文件,解决django自带的css按钮样式(具体表现为按钮字体上下不居中)覆盖kindeditor样式.

  • base.css
1
2
3
4
5
6
7
8
9
10
/* FORM BUTTONS */
.button, input[type=submit], input[type=button], .submit-row input, a.button {
background: #79aec8;
/*padding: 10px 15px;*/ /*解决字体部居中问题*/
border: none;
border-radius: 4px;
color: #fff;
cursor: pointer;
}