使用django富文本编辑器ckeditor

django富文本编辑器

1. djang-ckeditor

pip install django-ckeditor
# 在installed_apps 里面配置'ckeditor',修改LANGUEAGE_CODE = 'zh-hans' 注意:小写
pip install Pillow
# 在 installed_apps 里面配置'ckeditor_uploader'
# 继续配置上传路径:
CKEDITOR_UPLOAD_PATH = 'upload/'  # 默认上传到media下
# 在urls.py 中添加:
path('ckeditor/', include('ckeditor_uploader.urls'))
# 使用:
from ckeditor_uploader.fields import RichTextUploadingField
# 使用上面的作为字段的文本,在后台就可以上传图片和修改格式了

2. settings的其他配置

# 富文本编辑器配置图片保存路径
CKEDITOR_UPLOAD_PATH = "ckeditor/"
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'full',
        # 'toolbar': 'Custom',
        # 'toolbar_Custom': [
        #     ['Bold', 'Italic', 'Underline'],
        #     ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter',
        #      'JustifyRight', 'JustifyBlock'],
        #     ['Link', 'Unlink'],
        #     ['RemoveFormat', 'Source']
        # ],
        'height': 800,
        'width': 1000
    },
}

3. 将 django-ckeditor 接入项目字段的方法

  1. 直接把text用RichTextUploadingField

    from django.db import models
    from ckeditor_uploader.fields import RichTextUploadingField
    
    # 注意用 ckeditor.fields.RichTextUploadingField 是不能上传图片的
    
    
    class Blog(models.Model):
        text = RichTextUploadingField()
  2. 直接在forms中把text定义成 RichTextUploadingField ,这样在admin显示的时候把该form加进入就行了,同样能达到效果

    
    # admin.py
    
    from django import forms
    from django.contrib import admin
    from ckeditor_uploader.widgets import CkeditorUploadingWidget
    
    # 如果这里使用 ckeditor.widgets.CkeditorUploadingWidget,就不能上传图片
    
    
    from institution.models import Institution
    
    class InstitutitonForm(forms.ModelForm):
        brief = forms.CharField(widget=CkeditorUploadingWidget())
    
        class Meta:
            model = Institution
            fields = "__all__"
    
    class InstitutionAdmin(admin.ModelAdmin):
        form = InstitutionForm
    
    admin.site.register(Institution, InstitutionAdmin)

你可能感兴趣的:(探索Django,python)