07 后台管理页面

编辑本博客

富文本编辑器

官网:http://kindeditor.net/demo.php

使用文档:http://kindeditor.net/docs/usage.html

清空编辑器内容

window.editor.html("");

文件上传

 配置文件文件中添加uploadJson配置

配置csrf_token

上传文件,并返回路径

view视图,获取文件并存储,返回json数据,指定url

def upload(request):
    img=request.FILES.get('upload_img')
    response={'error':0,'url':"/media/add_article_img/%s" % img.name}
    path=os.path.join(settings.MEDIA_ROOT,'add_article_img',img.name)
    with open(path,'wb') as f:
        for line in img:
            f.write(line)
    return JsonResponse(response)
View Code

前端JavaScript代码

<script>
    $("#submit_btn").click(function () {
        var title = $("input[name='title']").val();
        var artivle_content = $("#editor_id").val();
        var csrfmiddlewaretoken = $('input[name="csrfmiddlewaretoken"]').val();
        if (title == "") {
            alert("标题不能为空")
        } else {
            if (artivle_content == "") {
                alert("内容不能为空")
            } else {
                $.ajax({
                    url: '',
                    type: 'post',
                    data: {
                        'title': title,
                        'artivle_content': artivle_content,
                        'csrfmiddlewaretoken': csrfmiddlewaretoken
                    },
                    success: function (data) {
                        console.log(data)
                    },
                    error: function (err) {
                        console.log(err)
                    }
                })
            }
        }
    })
</script>
View Code

 desc内容

不能直接截断content内容,content内容有标签

需通过bs4处理

from bs4 import BeautifulSoup

view代码

def add_article(request):
    if request.method=='POST':
        print(request.POST)
        title=request.POST.get('title')
        content=request.POST.get("artivle_content")
        soup=BeautifulSoup(content,'html.parser')
        desc=soup.text[:120]
        models.Article.objects.create(title=title,desc=desc,content=content,user_id=request.user.pk)
    return render(request,'add_article.html')
View Code

博客主体过滤

通过bs4过滤script标签,比较用户将script代码存入数据库

在desc数据截取功能上添加script标签过滤

def add_article(request):
    if request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get("artivle_content")
        soup=BeautifulSoup(content,'html.parser')
        #过滤script标签
        for tag in soup.find_all():
            if tag.name=="script":
                tag.decompose()#在soup对象中将script标签删除
        content=str(soup)
        #截取内容
        desc=soup.text[:120]
        models.Article.objects.create(title=title,desc=desc,content=content,user_id=request.user.pk)
        return JsonResponse({"msg":'博客添加成功!'})
    return render(request,'add_article.html')
View Code

前端代码不变

posted @ 2018-07-29 22:37  丫丫625202  阅读(118)  评论(0编辑  收藏  举报