在Django中集成CKEditor5并实现博客文章编辑与展示
在Django项目中集成CKEditor5以提供富文本编辑功能,可以显著提升用户体验。以下是完整的配置和使用步骤:
- 安装CKEditor5对应的Django包:
sudo pip3 install django-ckeditor-5
- 在
settings.py文件中将django_ckeditor_5添加到INSTALLED_APPS列表中:
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_ckeditor_5', # 添加此项
...
]
- 配置CKEditor5的设置项(示例配置):
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
custom_palette = [
{'color': 'hsl(4, 90%, 58%)', 'label': '红色'},
{'color': 'hsl(340, 82%, 52%)', 'label': '粉色'},
{'color': 'hsl(291, 64%, 42%)', 'label': '紫色'}
]
RICH_TEXT_CONFIGS = {
'basic': {
'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote'],
},
'advanced': {
'blockToolbar': ['paragraph', 'heading1', 'heading2', '|', 'bulletedList', 'numberedList', '|', 'blockQuote'],
'toolbar': [
'heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'underline', 'strikethrough', 'code',
'subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage',
'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|',
'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable'
],
'image': {
'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side'],
'styles': ['full', 'side', 'alignLeft', 'alignRight', 'alignCenter']
},
'table': {
'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties'],
'tableProperties': {'borderColors': custom_palette, 'backgroundColors': custom_palette},
'tableCellProperties': {'borderColors': custom_palette, 'backgroundColors': custom_palette}
},
'fontFamily': {
'options': ['微软雅黑', '宋体', '黑体', '仿宋', '楷体', 'Arial', 'Times New Roman'],
'supportAllValues': True
},
'fontSize': {
'options': [
{'model': '56px', 'title': '初号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '48px', 'title': '小初', 'view': {'styles': {'font-size': '14px'}}},
{'model': '34.7px', 'title': '一号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '32px', 'title': '小一', 'view': {'styles': {'font-size': '14px'}}},
{'model': '29.3px', 'title': '二号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '24px', 'title': '小二', 'view': {'styles': {'font-size': '14px'}}},
{'model': '21.3px', 'title': '三号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '20px', 'title': '小三', 'view': {'styles': {'font-size': '14px'}}},
{'model': '18.7px', 'title': '四号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '16px', 'title': '小四', 'view': {'styles': {'font-size': '14px'}}},
{'model': '14px', 'title': '五号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '12px', 'title': '小五', 'view': {'styles': {'font-size': '14px'}}},
{'model': '10px', 'title': '六号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '8.7px', 'title': '小六', 'view': {'styles': {'font-size': '14px'}}},
{'model': '7.3px', 'title': '七号', 'view': {'styles': {'font-size': '14px'}}},
{'model': '6.7px', 'title': '八号', 'view': {'styles': {'font-size': '14px'}}}
],
'supportAllValues': True
}
}
}
- 修改项目的
urls.py文件以支持CKEditor5的静态资源和媒体文件:
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('ckeditor5/', include('django_ckeditor_5.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 在应用的
models.py中定义一个模型类来存储文章内容:
from django.db import models
from django_ckeditor_5.fields import CKEditor5Field
class Article(models.Model):
title = models.CharField(max_length=200, verbose_name='标题')
content = CKEditor5Field(config_name='advanced', verbose_name='内容')
def __str__(self):
return self.title
- 创建表单类以便于在前端页面中使用CKEditor5:
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ('title', 'content')
widgets = {
'content': forms.Textarea(attrs={'class': 'django_ckeditor_5'})
}
- 在
admin.py中注册模型并配置管理界面:
from django.contrib import admin
from .models import Article
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'content')
- 更新数据库结构并收集静态文件:
python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic
- 在应用的
views.py中创建视图函数用于处理文章提交和展示:
from django.shortcuts import render, get_object_or_404
from .forms import ArticleForm
from .models import Article
def create_article(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'form-post-finished.html')
else:
form = ArticleForm()
return render(request, 'create-article.html', {'form': form})
def article_list(request):
articles = Article.objects.all()
return render(request, 'article-list.html', {'articles': articles})
def view_article(request, article_id):
article = get_object_or_404(Article, id=article_id)
return render(request, 'view-article.html', {'article': article})
- 配置应用的
urls.py以映射上述视图函数:
from django.urls import path
from . import views
urlpatterns = [
path('create/', views.create_article, name='create_article'),
path('list/', views.article_list, name='article_list'),
path('view/<int:article_id>/', views.view_article, name='view_article')
]
- 创建HTML模板文件以呈现表单和文章列表:
<!-- create-article.html -->
<form method="post">
{% csrf_token %}
<p>标题:{{ form.title }}</p>
<p>内容:{{ form.content }}</p>
<button type="submit">提交</button>
</form>
<!-- article-list.html -->
{% for article in articles %} - [{{ article.title }}](<{% url 'view_article' article.id %}>)
{% endfor %}
<!-- view-article.html -->
<h1>{{ article.title }}</h1>
<div>{{ article.content|safe }}</div>
至此,您已经成功集成了CKEditor5并在Django中实现了简单的博客功能。