欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django使用ckeditor上传图片

程序员文章站 2022-04-05 11:26:17
1、在模型类中设置字段为富文本类型,这里需要注意引入的是RichTextUploadingField,以允许上传图片,需要和RichTextField区分开 2、项目中ckeditor的安装及配置 CKEDITOR_UPLOAD_PATH = '' # 图片ckeditor文件上传路径,这里使用七牛 ......

1、在模型类中设置字段为富文本类型,这里需要注意引入的是richtextuploadingfield,以允许上传图片,需要和richtextfield区分开

from ckeditor_uploader.fields import richtextuploadingfield
class spit_model(models.model): """模型类""" user = models.foreignkey(user, on_delete=models.cascade,verbose_name='吐槽发布者') content = richtextuploadingfield(verbose_name='吐槽内容', max_length=200)

2、项目中ckeditor的安装及配置

pip install django-ckeditor
installed_apps = [
    ...
  'ckeditor', # 富文本编辑器   'ckeditor_uploader', # 富文本编辑器上传图片模块 ... ]
# 富文本编辑器ckeditor配置
ckeditor_configs = {
    'default': {
        'toolbar': 'full',  # 工具条功能
        'height': 300,  # 编辑器高度
        'width': 300,  # 编辑器宽
    },
}

 ckeditor_upload_path = ''  # 图片ckeditor文件上传路径,这里使用七牛云存储,不填

2、html页面中加入textarea标签

<div>
<textarea id="editor_id"></textarea>
</div>

3、页面中引入控制html页面的js和ckeditor的js文件, 在django的installed_app中注册应用时,会自动在虚拟环境中生成应用信息/home/python/.virtualenvs/django_1.11.16_py3/lib/python3.5/site-packages/ckeditor/static/ckeditor/ckeditor/

在js路径前加上域名,否则服务器会在live-server的默认端口下进行网络通讯,查找js
<script type="text/javascript" src="js/spit-submit.js"></script>
<script src="http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js"></script>

4、在vue变量的mounted方法中加入

let vm = new vue({
  ...
    mounted:function () {
        ckeditor.replace('editor_id', { filebrowseruploadurl:'http://127.0.0.1:8000/ckeditor/upload/' }); // 将id选择器的文本域替换成为富文本,并手动设置文件上传的请求路径,默认请求路径为live-server的路径,必须设置为服务器的域名和端口
    },
});

5、后端设置总路由,'ckeditor_uploader.urls'中会将接收到的请求进行csrf校验免除,并限制了只有登录用户才可以上传图片,ckeditor默认应用的是django-admin的用户校验方法,django-admin的校验方法不允许跨域请求,我们需要使上传图片的类试图函数继承自django-restframework的apiview,

   # url(r'^ckeditor/', include('ckeditor_uploader.urls')),  # 为富文本编辑器添加总路由
    # url(r'^ckeditor/upload/', imageuploadview.as_view()),  # 为富文本编辑器添加总路由
    # url(r'^ckeditor/upload/', csrf_exempt(imageuploadview.as_view())),  # 为富文本编辑器添加总路由
    url(r'^ckeditor/', csrf_exempt(imageuploadview.as_view())),  # 为富文本编辑器添加总路由

6、在应用中改写路由和类视图,使用permission_classes对请求权限进行限制

# 配置路由
urlpatterns = [
    url(r'^upload/$', imageuploadview.as_view()),
]


from ckeditor_uploader import image_processing,utils
from django.conf import settings
from django.http import httpresponse
from django.http import jsonresponse
from rest_framework.permissions import isauthenticated
from rest_framework.views import apiview
from django.utils.html import escape


class imageuploadview(apiview):
    permission_classes = [isauthenticated]
    http_method_names = ['post']

    def post(self, request, **kwargs):
        """
        uploads a file and send back its url to ckeditor.
        """
        uploaded_file = request.files['upload']

        backend = image_processing.get_backend()

        ck_func_num = request.get.get('ckeditorfuncnum')
        if ck_func_num:
            ck_func_num = escape(ck_func_num)

        # throws an error when an non-image file are uploaded.
        if not getattr(settings, 'ckeditor_allow_nonimage_files', true):
            try:
                backend.image_verify(uploaded_file)
            except utils.notanimageexception:
                return httpresponse("""
                    <script type='text/javascript'>
                    window.parent.ckeditor.tools.callfunction({0}, '', 'invalid file type.');
                    </script>""".format(ck_func_num))

        saved_path = self._save_file(request, uploaded_file)
        if len(str(saved_path).split('.')) > 1:
            if(str(saved_path).split('.')[1].lower() != 'gif'):
                self._create_thumbnail_if_needed(backend, saved_path)
        url = utils.get_media_url(saved_path)

        if ck_func_num:
            # respond with javascript sending ckeditor upload url.
            return httpresponse("""
            <script type='text/javascript'>
                window.parent.ckeditor.tools.callfunction({0}, '{1}');
            </script>""".format(ck_func_num, url))
        else:
            retdata = {'url': url, 'uploaded': '1',
                       'filename': uploaded_file.name}
            return jsonresponse(retdata)