Django使用summernote富文本编辑器,完整前后端

今天项目中要使用summernote富文本编辑器,由于网上的基本都是在说用这个编辑器上传图片的,所以我就整理了一下上传图片和文本的代码,完整前后端。

这里我准备了一个demo,需要的可以直接复制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Summernote</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.css" rel="stylesheet">
    <script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.js"></script>
</head>
<body>
<div style="width: 60%;margin:20px auto" >
    <div id="summernote"></div>
</div>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height : '200px',
            placeholder: 'Hello hello hello ...',
            lang : 'zh-CN',
            callbacks: {
                onImageUpload: function(files, editor, $editable) {
                    sendFile(files);
                }
            },
            toolbar: [
                          [ 'style', [ 'style' ] ],
                          [ 'font', [ 'bold', 'italic',  'clear'] ],
                          [ 'fontname', [ 'fontname' ] ],
                          [ 'fontsize', [ 'fontsize' ] ],
                          [ 'color', [ 'color' ] ],
                          [ 'para', [ 'ol', 'ul', 'paragraph', 'height' ] ],
                          ['picture'],
                          [ 'table', [ 'table' ] ],
                          [ 'insert', [ 'link'] ],
                          [ 'view', [ 'undo', 'redo', 'fullscreen', 'codeview', 'help' ] ]
				          ]

        });
    });
</script>
</body>
</html>

这是富文本编辑器的效果图
在这里插入图片描述
下面附上js代码,包括提交图片和文本


<form id="ftn">
      {% csrf_token %}
      <div>
      		<input type="text" id="title" name="title" placeholder="请输入帖子标题"/>
      		<div>
                  <input class="summernote" id="summernote" name="content">
            </div>
       </div>
       <button type="button" onclick="save()">提交</button>
 </form>

<script>
    /**
     * 编辑器新增的ajax上传图片函数
     * @param files
     * @param editor
     * @param $editable
     * @returns {boolean}
     */
    function sendFile(files, editor, $editable) {
        var size = files[0].size;
        if((size / 1024 / 1024) > 2) {
            alert("图片大小不能超过2M...");
            return false;
        }
        var formData = new FormData();
        formData.append("file", files[0]);
        $.ajax({
            data : formData,
            type : "POST",
            url : "/instantuploa/",    // 图片上传出来的url,返回的是图片上传后的路径,http格式
            cache : false,
            contentType : false,
            processData : false,
            dataType : "json",
            success: function(response) {//data是返回的hash,key之类的值,key是定义的文件名
                if (response['status'] == 1){
                    //将图片插入到编辑框内
                    $('#summernote').summernote('insertImage', response.file, 'img');
                }else{
                    alert('上传失败,请重新上传!');
                    return false
                }
            },
            error:function(){
                alert("上传失败");
            }
        });
    }
    function save() {
        var tet = $('#summernote').summernote('code' );
        var title = $('#title').val();
        var data = {
            content : tet,
            title : title,
        };
        console.log(data);
        $.ajax({
            cache: true,
            type: 'POST',
            url:'/text/',
            data:data,
            success:function (data) {
				//写上你的回调处理
            }
        })
    }
</script>

接下里是Django后端的接收代码

from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exemp

@login_required
@csrf_exempt
def text(request):
    # 获取富文本编辑器中的数据
    if request.method == "POST":
        title = request.POST.get('title')
        print(title)
        content = request.POST.get('content')
        print(content)
    return render(request,'index.html')

# 上传图片
@login_required
@csrf_exempt
def instantuploa(request):
    if request.method == 'POST':
        # 拿到图片对象
        content_img = request.FILES['file']
        # 判断图片大小
        if content_img.size/1024/1024 < 2:
            # 判断图片格式是否为规定的格式
            if content_img.content_type == 'image/jpeg' or content_img.content_type == 'image/jpg' or content_img.content_type == 'image/png':
                # 获取当前结构化时间用于拼接图片名称
                nowtime = datetime.datetime.now().strftime('%Y%m%d%H%S')
                # 创建一个文件
                path = os.path.join(settings.MEDIA_ROOT,nowtime + content_img.name)
                # 写文件 遍历图片文件流
                with open(path, 'wb') as f:
                    for content in content_img.chunks():
                        f.write(content)
                # 关闭文件流
                f.close()
                # 拼接文件名和路径
                user_img = '图片存放的路径{}'.format(nowtime + content_img.name)
                # 返回图片路径
                response = {
                    "status": 1,
                    "message": "上传成功",
                    'file': user_img,
                }
                return HttpResponse(json.dumps(response))

            else:
                response={
                    "status": 0,
                    "message": "只能上传jpeg、jpg、png格式的图片!",
                }
                return HttpResponse(json.dumps(response))
        else:
            response = {
                "status": 0,
                "message": "图片超过了2M!",
            }
            return HttpResponse(json.dumps(response))

图片上传的具体设置步骤请参考:https://blog.csdn.net/weixin_45457042/article/details/103975741
希望对您有所帮助。有疑问可以留言。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值