简易博客开发(5)----django集成kindeditor富文本编辑及代码高亮

KindEditor 是一套开源的在线HTML编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用 KindEditor 把传统的多行文本输入框(textarea)替换为可视化的富文本输入框。 官网地址http://kindeditor.net/doc.php

这边需要用到第三方的源码及文件,此时要在项目应用中新建一个static目录来存放这些静态文件,同时修改settings.py来让django能够找到static静态文件

#/myblog/myblog/settings.py
101 # https://docs.djangoproject.com/en/1.8/howto/static-files/                    
102 
103 STATIC_URL = '/static/'                                                        
104 
105 STATICFILES_DIRS = (
106     os.path.join(BASE_DIR, "static"),
107 )

官网下载kindEditor 4.1.10命名为kindeditor放在/myblog/myblog/blog/static文件夹下,修改post.html把textarea改成kindeditor

1 {% extends "base.html" %}
  2 {% block content %}
  3 <script type="text/javascript" charset="utf8" src="/static/kindeditor/kindeditor.js"></script>       #引用kindeditor.js
  4 <script type="text/javascript" charset="utf8" src="/static/kindeditor/lang/zh_CN.js"></script>       #引用zh_CN.js
  5 <script>                   
  6     var editor;
  7     KindEditor.ready(function(K){
  8         editor = K.create('textarea[name="content"]',{                                               #textarea的name必需为content才可以正确替代,也可以用id,则为#
  9
 10         });
 11     });
 12 </script>
 13 <div class = "posts">
 14     <section class="post">
 15         <form action={% url 'blog_add' %} class="pure-form pure-form-stacked" method="post">
 16         <label>title</label>
 17         <input class="pure-input-1-4" name="title" type="text">
 18         <label>tags</label>
 19         <input class="pure-input-1-4" name="tags" type="text">
 20         <label>content</label>
 21         <textarea style="width:700px;height:400px;"  name='content'>&lt;strong&gt;HTML&lt;/strong&gt;</textare  #teatarea在这里替换成kindeditor
    a>      
 22         <button class="pure-button" type="submit">Submit</button>
 23         </form>
 24     </section>
 25 {% endblock %}
替换后的效果

增加插入代码高亮功能,原本只是想prettyPrint这种做法,后来发现不好,与SyntaxHighlighter差距不小,于是改用SyntaxHighlighter,原理是当在kindeditor中插入代码,代码内容被嵌套在<pre></pre>标签,因此只要给pre适当的css即可实现,当然要加上语言语法要更加难点,第三方syntaxhighlighter很方便

下载SyntaxHighter放入myblog/blog/static文件夹下,

#/myblog/blog/templates/detail.html  
  1 {% extends "base.html" %}
  2 {% block content %}
  3 <script type="text/javascript" src="/static/syntaxhighlighter/scripts/shCore.js"></script>              #shCore.js
  4 <script type="text/javascript" src="/static/syntaxhighlighter/scripts/shBrushPython.js"></script>       #shBrushPython.js
  5 <link href="/static/syntaxhighlighter/styles/shCoreDefault.css" rel="stylesheet" type="text/css" />     #shCoreDefault.css
  6 <link href="/static/syntaxhighlighter/styles/shThemeDefault.css" rel="stylesheet" type="text/css" />    #shThemeDefault.css
  7 <div class = "posts">
  8     <section class="post">
  9         <header class="post-header">
 10             <h2 class= "post-title">{{blog.title}}<h2>
 11                 <p class = "post-meta">
 12                     Time: <a class="post-author" href="#">{{blog.date_time | date:'Y M d'}}</a>&nbsp
 13                     Tag:
 14                     {% for tag in blog.tags.all  %}
 15                     <a class="post-category" href="#">{{tag.tag_name}}</a>
 16                     {% endfor %}
 17                 </p>
 18         </header>
 19 
 20             <div class="post-description">
 21                 <p>
 22                     {{blog.content|safe}}
 23                 </p>
 24             </div>
 25     </section>
 26 <script type="text/javascript">SyntaxHighlighter.all();</script>                                         #调用SyntaxHightlighter.all()函数
 27 {% endblock %}
测试结果

在kindEditor上传图片,修改post.html中kindeditor部分,增加上传图像方法


#/myblog/blog/templates/post.html  
  5 <script>                   
  6     var editor;
  7     KindEditor.ready(function(K){
  8         editor = K.create('textarea[name="content"]',{        #textarea的name必需为content才可以正确替代
  9             uploadJson: '/blog/uploadImg/',                   #用json进行上传,直接跳转到后台用uploadImg方法去实现                 
 10         });
 11     });
 12 </script>
由于增加了方法,url, views都需要修改
#/myblog/blog/urls.py
  1 from django.conf.urls import patterns, include, url                            
  2                                                                                
  3 from django.contrib import admin                                               
  4                                                                                
  5 from blog import views                                                         
  6                                                                                
  7 urlpatterns =[                                                                 
  8     url(r'^$', views.index, name='index'),                                     
  9     url(r'^(?P<id>(\d+))/$', views.detail, name='detail'),                     
 10     url(r'^post/$', views.post, name='post'),                                  
 11     url(r'^blog_add/$', views.blog_add, name='blog_add'),                      
 12     url(r'^uploadImg/$', views.uploadImg,name='uploadImg'),              #新增上传图片方法                  
 13 ]
增加上uploadImg函数
#/myblog/blog/views.py 
 48 #uploadImg 
 49 def mkdir(path):                                         #路径初始化,如果没有存放地点就新建
 50     path = path.strip()
 51     path = path.rstrip("\\")
 52     if not os.path.exists(path):
 53         os.makedirs(path)
 54     return path
 55     
 56 def save_file(path, file_name, data):                   #把data保存path/file_name文件中
 57     if data == None:
 58         return
 59     mkdir(path)
 60     if(not path.endswith("/")):
 61         path=path+"/"
 62     file = open(path+file_name,"wb")                                           
 63     file.write(data)
 64     file.flush()                                                               
 65 
 66 def uploadImg(request):
 67     if request.method=='POST':                                                 
 68         file_obj = open("log.txt","w+")
 69         buf = request.FILES.get('file',None)                                    #获取的图片文件
 70         print >> file_obj, str(buf)                                            
 71         file_buff = buf.read()                                                  #获取图片内容
 72         time_format=str(time.strftime("%Y-%m-%d-%H%M%S",time.localtime()))     
 73         file_name = "img"+time_format+".jpg"                                    #img2016-02-13-072459.jpg                                
 74         save_file("blog/static/image", file_name,file_buff)                     #blog/static/image/img2016-02-13-072459.jpg                 
 75         dict_tmp = {}                                                           #kindeditor定义了返回的方式是json,
 76         dict_tmp['error']=0                                                     #成功{ "error":0, "url": "/static/image/filename"}
 77         dict_tmp['url']="/static/image/"+file_name
 78         return HttpResponse(json.dumps(dict_tmp))
上传图片结果

富文本编辑实现了代码高亮,图片上传基本功能,下一节说一说评论系统



转载于:https://my.oschina.net/hding/blog/614663

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值