先從官網下載插件,放在static文件下javascript
前端引入php
<script type="text/javascript" src="/static/back/kindeditor/kindeditor-all.js"></script> <script> KindEditor.ready(function (K) { window.editor = K.create('#content', { {# 加上這句話能夠使jquery能獲取到富文本編輯器的內容#} afterBlur: function(){this.sync();}, width: "800", height: "600", resizeType: 0, uploadJson: "/back/article/upload/", extraFileUploadParams: { csrfmiddlewaretoken: "{{ csrf_token }}" }, filePostName: "upload_img"//上傳圖片的名稱 }); }); </script>
定義富文本編輯器在頁面中的位置html
<textarea id="content" name="content" style="width:700px;height:250px;"></textarea>
ajax提交前端
#提交按鈕 <input name="dosubmit" type="button" id="dosubmit" class="btn" value="立刻發佈"> # 提交富文本編輯器的內容 <script> {# 提交文章#} $('#dosubmit').click(function () { $.post('/back/article/back_add/',$('form').serialize(),function (data) { if (data['status']==0){ layer.msg(data['info']) {#location.href="/back/index/index/"#} }else{ layer.msg(data['info']) } },'json') }) </script>
路由java
# 富文本編輯器 re_path('article/upload/', article.upload, name='article/upload/'), # 接受form表單內容添加文章 re_path('article/add/', article.add, name='article/add/'),
後臺接收圖片方法jquery
#富文本編輯器裏上傳圖片 import os def upload(request): """ 編輯器上傳文件接受視圖函數 :param request: :return: """ # print(request.FILES) img_obj=request.FILES.get("upload_img") # print(img_obj.name) path=os.path.join(settings.MEDIA_ROOT,"add_article_img",img_obj.name) with open(path,"wb") as f: for line in img_obj: f.write(line) response={ "error":0, "url":"/media/add_article_img/%s"%img_obj.name } return HttpResponse(json.dumps(response))
後臺接收內容方法ajax
def add(request): member_obj=Member.objects.all() member_id = request.session.get('member_id') member_name=request.session.get('member_name') if request.method == 'POST': title = request.POST.get("title") description = request.POST.get('description') content = request.POST.get("content") addtime=time.strftime('%Y-%m-%d',time.localtime()) # 防止xss攻擊,過濾script標籤 soup=BeautifulSoup(content,"html.parser")#經過字符串建立BeautifulSoup對象,即將字符串轉爲對象,而後調用對象裏的相關方法 print(soup.find_all())#[<img alt="" src="/media/add_article_img/hand.png"/>, <script charset="utf-8" src="/static/blog/kindeditor/kindeditor-all.js"></script>,<img src="/media/add_article_img/thumb_50_img1.jpg" alt="" />] for tag in soup.find_all(): print(tag.name)#img script if tag.name=="script": tag.decompose() # # 構建摘要數據,獲取標籤字符串的文本前150個符號 desc = soup.text[0:150] + "..." obj=Article.objects.create(article_title=title,article_description=desc,article_content=str(content),member_id=member_id,article_addtime=str(addtime).replace('/','-')) if obj: return redirect('/back/article/add/') return render(request,'article/add.html',locals())
頁面效果json
done。session