从0到1搭建个人网站 八-django 中集成 ckeditor
优质
小牛编辑
127浏览
2023-12-01
安装ckeditor
django集成ckeditor已经有人帮我们做了,我们直接参考https://github.com/django-ckeditor/django-ckeditor安装,方法如下:
pip install django-ckeditor
然后修改shareditor/settings.py中的INSTALLED_APPS,添加如下项:
? ? 'ckeditor',
? ? 'ckeditor_uploader',
再在shareditor/settings.py中添加:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
CKEDITOR_UPLOAD_PATH = 'ckeditor_images'
CKEDITOR_CONFIGS = {
'default': {
'skin': 'moono',
'toolbar_YourCustomToolbarConfig': [
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript']},
{'name': 'links', 'items': ['Link', 'Unlink']},
{'name': 'insert',
'items': ['CodeSnippet', 'Image', 'Table', 'PageBreak']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
'tabSpaces': 4,
'extraPlugins': ','.join([
'uploadimage', # the upload image feature
'div',
'autolink',
'autoembed',
'embedsemantic',
'autogrow',
'widget',
'dialog',
'lineutils',
'codesnippet'
]),
'codeSnippet_theme': 'atelier-dune.dark',
}
}
修改urls.py,改为:
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
......
url(r'^ckeditor/', include('ckeditor_uploader.urls'))
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
然后执行如下命令来拷贝静态文件:
./manage.py collectstatic
为了在管理界面能展示ckeditor,我们将model中的富文本字段改成:
from ckeditor_uploader.fields import RichTextUploadingField
body = RichTextUploadingField(config_name='default', verbose_name='文章内容')
(这里的default要和settings.py文件里的CKEDITOR_CONFIGS对应)
然后在文章的展示模板里要添加:
{% load static %}
{% block head %}
<link href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/atelier-dune.dark.css' %}" rel="stylesheet">
<script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script>
<script>hljs.initHighlightingOnLoad();</script>
{% endblock %}
效果展示
管理界面如下:
博客展示页面如下:
文件上传对接阿里oss
考虑到我们的服务需要部署在多台机器,图片静态文件上传后还要共享到每台服务器的方案不是很合理,而且没有cdn支持,所以我们自定义文件上传接口来实现文件上传到阿里云的oss对象存储服务
修改web/views.py,实现自定义的文件上传方法如下:
from commons.ossutils import upload_oss
BucketName = 'shareditor-shareditor'
def body_upload(request):
print request.FILES
if 'upload' in request.FILES:
image_name = request.FILES['upload'].name
image_content = request.FILES['upload'].read()
url = upload_oss(BucketName, image_name, image_content)
if url:
return render(request, 'web/body_upload.html', {'url': url})
return HttpResponse('upload fail')
这里的web/body_upload.html模板实现如下:
<script type='text/javascript'>
? ? window.parent.CKEDITOR.tools.callFunction(1, "{{ url }}");
</script>
在urls.py中增加路由:
url(r'^uploader/body_upload', views.body_upload, name='body_upload'),
修改ckeditor的配置,增加:
'filebrowserUploadUrl': '/uploader/body_upload',
现在我们在ckeditor中上传图片,就会自动上传到阿里云oss啦