美文网首页pycharm
2018-06-13 django的admin中使用KindEd

2018-06-13 django的admin中使用KindEd

作者: longshelan_113 | 来源:发表于2018-06-14 10:58 被阅读109次

    由于django后台管理没有富文本编辑器,展示出来的页面不美观,所以我们想要引入第三方富文本编辑器。网上搜寻了一番,但还是有些问题,不能完全适用,自己就把遇到的问题总结一下吧。

    一开始没有想到用哪种,同事说kindeditor吧,那我就好吧,就直接用这个吧,我是有多懒-_-||

    文本编辑器。之所以选择这个编辑器主要看是它功能齐全还美观。下面这张图是kindeditor的样子,没错功能就是这么多,外观就是这么好看。

    本地环境是Anaconda3的Python3环境,为了项目昨天搭建了Python2的环境+django,所以整个环境是Python2.7.15+django1.11.10+Pycharm2018.1.3

    好了开始我们的django 使用kindeditor之路。

    第一步,到官网下载kindeditor 

    第二步,下载到本地后,删除无用项

    第三步,把剩余文件引入到项目中去

    django中配置

     第一步:在setting.py中配置静态文件上传目录,编辑器中上传的文件将保存在这里。

    STATIC_URL = '/static/'

    STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )

     第二步:在项目的urls.py配置文件中配置

    url(r'^uploads/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),

    出错的地方也是这里,网上找的资料是下面这种写法,但是在我的环境中会报错,报TypeError: view must be a callable or a list/tuple in the case of include().

    url(r'^uploads/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),

    后来查了半天才发现,django1.10不再支持 url(r'^uploads/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),这种用法了

    第三步:在自己的应用中的view.py中加入下面的代码(ps:这段代码我是网上找的)

    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):

        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', 'zip', "swf", "flv",

                        "mp3", "wav", "wma", "wmv",

                        "mid", "avi", "mpg", "asf",

                        "rm", "rmvb", "doc", "docx",

                        "xls", "xlsx", "ppt", "htm",

                        "html", "txt", "zip", "rar",

                        "gz", "bz2"]

        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}

    第四步:配置应用中的url

    from app.viewsimport upload_image

    urlpatterns = [

    url(r'^upload/(?P[^/]+)$', upload_image, name='upload_image'),

    ]

    第五步,在kindeditor-4.1.11文件下新建一个config文件

    KindEditor.ready(function (k) {

    window.editor = k.create('#id_profile',{

    resizeType:1,

            allowPreviewEmoticons :false,

            allowImageRemote :false,

            uploadJson :'/upload/kindeditor',

            width:'800px',

            height:'400px',

        });

    })

    这边的“id_profile”是我需要把text变成富文本的元素的id,根据你的需要来填写,例如后面我换了个元素,这个id值也变了

    网上有建议将settings.py中间件的crsf注释掉,说是有可能post请求会报错,目前mei没发现问题,后面若发现问题,我就把它注释掉。

    第六步,去admin.py中注册模型类。将其kindeditor的js文件引入到admin中

    导入模型类,这里我的模型类是UserInfo ,这个按照自己的模型类修改就可以了。原来的# admin.site.register(UserInfo) 这样的注册方法直接注释掉

    from django.contrib import admin

    @admin.register(UserInfo)

    class UserInfoAdmin(admin.ModelAdmin):

    # list_display = ['title']

        class Media:

    def __init__(self):

    pass

            js = (

    '/static/js/kindeditor-4.1.11/kindeditor-all.js',

                '/static/js/kindeditor-4.1.11/lang/zh_CN.js',

                '/static/js/kindeditor-4.1.11/config.js',

            )

    这边网上的资料看到的都会list_display = ['title']或者list_display = ('title'),但是我都试过,都会报错,所以只好注释掉

    因为不需要写页面,所以没写js文件,也没有jsp文件引用,不同字段引用,只能用不同的config,但如果一个Model中有多个字段要运用的,要怎么弄,暂时没想好[・_・?]

    我的模型类是这个,富文本编辑器是用在profile这个字段上。

    最后,起一下服务看一下效果

    可以加图片和表情,成功\(^o^)/

    每个人的环境啊多种因素,会导致代码的不通用,所以每个人还是根据自己的情况进行变通吧^_^

    相关文章

      网友评论

        本文标题:2018-06-13 django的admin中使用KindEd

        本文链接:https://www.haomeiwen.com/subject/cbjeeftx.html