用到的富文本编辑器是kindeditor,可以去官网下载,看看官方文档
前端
window.editor = K.create('#article_content',{
与textarea绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
}
.header {
width: 100%;
height: 60px;
background-color: #369;
}
.content {
margin: 20px auto;
width: 80%;
}
</style>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="header"></div>
<div class="content">
<h3>添加文章</h3>
<form action="" method="post">
{% csrf_token %}
<div>
<label for="">文章标题</label>
<input type="text" name="title" class="form-control" style="width: 200px;">
</div>
<div>
<p>内容(TinyMCE编辑器,支持拖放/粘贴上传图片)</p>
<textarea name="article_content" id="article_content" cols="60" rows="20"></textarea>
</div>
<input type="submit" class="btn btn-info">
</form>
</div>
<script charset="utf-8" src="/static/kindeditor/kindeditor-all-min.js"></script>
<script src="/static/jquery-3.3.1.js"></script>
<script>
KindEditor.ready(function(K) {
window.editor = K.create('#article_content',{
width:"900px",
height:"500px",
{#items:["map"],#}
uploadJson:"/upload/",
extraFileUploadParams:{
csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(),
},
filePostName:"upload_image",
});
});
</script>
</body>
</html>
后端
处理上传图片
from untitled2 import settings
import os
def upload(request):
print(request.FILES)
obj=request.FILES.get("upload_image")
print(obj)
# 文件上传
path = os.path.join(settings.MEDIA_ROOT,"add_article_image",obj.name)
with open(path,"wb") as f:
for line in obj:
f.write(line)
res={
"error":0,
"url":"/media/add_article_image/"+obj.name
}
return HttpResponse(json.dumps(res))
beautifulsoup
文章的描述需要截取文章的前150个字符,但是入过是简单的content[0:150]会出现把html标签也截取的情况,如果前端用safe过滤,前端页面会出现乱套(很多标签匹配乱了).这个时候就需要用到beautifulsoup.
首先pip install beautifulsoup4
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
bs = BeautifulSoup(article_content,"html.parser")
desc = bs.text[0:150]+"..."
article_obj = models.Article.objects.create(title=title,user=user,desc=desc)