• Django之富文本编辑器kindeditor 及上传


    1.什么是富文本编辑器

    百度百科(https://baike.baidu.com/item/%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8/10954999?fr=aladdin

    KindEditor 是一套开源的在线HTML编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用 KindEditor 把传统的多行文本输入框(textarea)替换为可视化的富文本输入框。 KindEditor 使用 JavaScript 编写,可以无缝地与 Java、.NET、PHP、ASP 等程序集成,比较适合在 CMS、商城、论坛、博客、Wiki、电子邮件等互联网应用上使用。

    2.Django配置

    2.1 配置static静态资源
    KindEditor是用JavaScript编写的,这属于static files,因此需要为Django设置static路径。 首先在工程目录下新建static文件夹,这里要注意的是千万不要在my_app/下创建static文件夹作为static文件存放的目录, 这会导致Django无法搜索到自己的static 文件。创建后好,在settings中配置static文件目录。添加以下代码
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR,  'static'),
    )
    
    MEDIA_URL = '/uploads/'
    
    MEDIA_ROOT = os.path.join(BASE_DIR,  'uploads')

    2.2 下载 

    http://kindeditor.net/down.php

    2.3 解压并复制到项目目录下

    2.4 定义Media类并编辑kindeditor配置

    class ArticleAdmin(admin.ModelAdmin):
    	list_display = ('title', 'desc','click_count','date_publish')#显示列
    	list_display_links = ('title', 'desc',)#显示列上的链接效果
    	list_editable = ('click_count',)#可编辑的列
    
    	fieldsets = (
    		(None, {
    			'fields': ('title', 'desc', 'content', 'user', 'category', 'tag',)
    		}),
    		('高级设置', {
    			'classes': ('collapse',),#折叠状态
    			'fields': ('click_count', 'is_recommend',)
    		}),
    	)
    
    	class Media:
    		js = (
    			'/static/js/kindeditor-4.1.10/kindeditor-min.js',
    			'/static/js/kindeditor-4.1.10/lang/zh_CN.js',
    			'/static/js/kindeditor-4.1.10/config.js',
    		)
    

    config.js

    KindEditor.ready(function (K) {
        K.create('textarea[name=content]', {/*css元素*/
             '800px',
            height: '200px',
            uploadJson: '/admin/upload/kindeditor',/*请求url*/
        });
    });
    

    2.5 配置url

    urlpatterns = [
    	url(r'^admin/', admin.site.urls),
    	url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload.upload_image, name='upload_image'),
    ]
    

    upload.py

    # -*- coding: utf-8 -*-
    from django.http import HttpResponse
    from django.conf import settings
    from django.views.decorators.csrf import csrf_exempt
    import os
    import uuid
    import json
    import datetime as dt
    
    @csrf_exempt
    def upload_image(request, dir_name):
        ##################
        #  kindeditor图片上传返回数据格式说明:
        # {"error": 1, "message": "出错信息"}
        # {"error": 0, "url": "图片地址"}
        ##################
        result = {"error": 1, "message": "上传出错"}
        files = request.FILES.get("imgFile", None)
        if files:
            result =image_upload(files, dir_name)
        return HttpResponse(json.dumps(result), content_type="application/json")
    
    #目录创建
    def upload_generation_dir(dir_name):
        today = dt.datetime.today()
        dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
        if not os.path.exists(settings.MEDIA_ROOT + dir_name):
            os.makedirs(settings.MEDIA_ROOT + dir_name)
        return dir_name
    
    # 图片上传
    def image_upload(files, dir_name):
        #允许上传文件类型
        allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
        file_suffix = files.name.split(".")[-1]
        if file_suffix not in allow_suffix:
            return {"error": 1, "message": "图片格式不正确"}
        relative_path_file = upload_generation_dir(dir_name)
        path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
        if not os.path.exists(path): #如果目录不存在创建目录
            os.makedirs(path)
        file_name=str(uuid.uuid1())+"."+file_suffix
        path_file=os.path.join(path, file_name)
        file_url = settings.MEDIA_URL + relative_path_file + file_name
        open(path_file, 'wb').write(files.file.read()) # 保存图片
        return {"error": 0, "url": file_url}

    3.测试

    4.参考

    http://kindeditor.net/docs/usage.html

    http://kindeditor.net/docs/upload.html

    https://docs.djangoproject.com/en/1.8/howto/static-files/

    https://docs.djangoproject.com/en/1.8/topics/forms/media/

  • 相关阅读:
    while(~scanf(..))为什么可以这样写
    【 HDU3294 】Girls' research (Manacher)
    【 HDU2966 】In case of failure(KD-Tree)
    【 HDU 1538 】A Puzzle for Pirates (海盗博弈论)
    【 HDU 2177 】取(2堆)石子游戏 (威佐夫博弈)
    【 HDU 4936 】Rainbow Island (hash + 高斯消元)
    【 HDU1081 】 To The Max (最大子矩阵和)
    Partition Numbers的计算
    【 HDU
    【 Gym 101116K 】Mixing Bowls(dfs)
  • 原文地址:https://www.cnblogs.com/jasonhaven/p/7515158.html
Copyright © 2020-2023  润新知