博客中嵌入富文本编辑器以及beautiulsoup的应用

用到的富文本编辑器是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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值