Integrácia CKEditor5 do Django projektu
Integrácia CKEditor5 do Django projektu
CKEditor5 umožňuje jednoducho pridávať bohatý textový editor do formulárov vo vašej Django aplikácii. Tu je postup na jeho integráciu:
Krok 1
Inštalácia knižnice cez pip
pip install django-ckeditor-5
Krok 2
Pridanie do INSTALLED_APPS
v settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# My site app
'peter_pekny_page', # my app
# virtual keyboard
'django_ckeditor_5', # CKEditor 5
# allauth
'django.contrib.sites', # allauth
'allauth', # allauth
'allauth.account', # allauth
'allauth.socialaccount', # allauth
'allauth.socialaccount.providers.google', # allauth
# 'allauth.socialaccount.providers.facebook', # allauth
'allauth.socialaccount.providers.github', # allauth
]
Krok 3
Nastavenie URL pre CKEditor.. V súbore urls.py
v hlavnom projekte pridaj:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# ckedior5
path("ckeditor5/", include('django_ckeditor_5.urls')),
# Add peter_pekny_page app to the urlpatterns list
path('', include('peter_pekny_page.urls')),
# path('editorjs/', include('django_editorjs2.urls')),
path('accounts/', include('allauth.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Krok 4
Nastavenie v settings.py
(voliteľná konfigurácia)
- nastavenie zobrazenia palety nastrojov.
# CKEDITOR_5_CUSTOM_CSS = 'path_to.css' # optional
CKEDITOR_5_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" # optional
CKEDITOR_5_CONFIGS = {
'default': {
'toolbar': ['heading', '|', 'bold', 'italic', 'link',
'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],
},
'comment': {
'toolbar': ['heading', '|', 'bold', 'italic', 'link',
'bulletedList', 'numberedList', 'blockQuote', 'imageUpload',
'highlight', 'horizontalLine', 'link','code', 'codeBlock' ],
},
'extends': {
'blockToolbar': [
'paragraph', 'heading1', 'heading2', 'heading3',
'|',
'bulletedList', 'numberedList',
'|',
'blockQuote',
],
'toolbar': ['heading', '|', 'outdent', 'indent', '|','SpecialCharacters', 'bold', 'italic', 'underline', 'strikethrough',
'|', 'alignment', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor','highlight', 'horizontalLine', 'link','code','subscript', 'superscript', '|', 'codeBlock', 'sourceEditing', 'insertImage',
'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', 'mediaEmbed', 'removeFormat',
'insertTable', '|', 'undo', 'redo' ],
'image': {
'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft',
'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'],
'styles': [
'full',
'side',
'alignLeft',
'alignRight',
'alignCenter',
]
},
# !!!!!!!! - mediaEmbed - enable previews in data !!!!!!!!
'mediaEmbed': {
'previewsInData': True # Enable previews in data !!!!!!!!
},
# !!!!!!!!
'table': {
'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells',
'tableProperties', 'tableCellProperties' ],
'tableProperties': {
'borderColors': customColorPalette,
'backgroundColors': customColorPalette
},
'tableCellProperties': {
'borderColors': customColorPalette,
'backgroundColors': customColorPalette
}
},
'heading' : {
'options': [
{ 'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph' },
{ 'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1' },
{ 'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2' },
{ 'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3' }
]
},
},
'list': {
'properties': {
'styles': 'true',
'startIndex': 'true',
'reversed': 'true',
}
},
'full': { # Plná konfigurácia (všetky nástroje)
'toolbar': [
'heading', '|', 'bold', 'italic', 'underline', 'strikethrough',
'subscript', 'superscript', '|', 'link', 'imageUpload', 'blockQuote',
'code', 'codeBlock', '|', 'bulletedList', 'numberedList', 'outdent', 'indent',
'|', 'alignment', 'horizontalLine', 'table', '|', 'undo', 'redo'
],
'image': {
'toolbar': ['imageTextAlternative', 'imageStyle:full', 'imageStyle:side']
},
'table': {
'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells']
},
'language': 'en',
}
}
# Define a constant in settings.py to specify file upload permissions
CKEDITOR_5_FILE_UPLOAD_PERMISSION = "any" # Possible values: "staff", "authenticated", "any"
extends:

comments:

settings.py
# CKEDITOR_5 - configuration for CKEditor 5
customColorPalette = [
{
'color': 'hsl(4, 90%, 58%)',
'label': 'Red'
},
{
'color': 'hsl(340, 82%, 52%)',
'label': 'Pink'
},
{
'color': 'hsl(291, 64%, 42%)',
'label': 'Purple'
},
{
'color': 'hsl(262, 52%, 47%)',
'label': 'Deep Purple'
},
{
'color': 'hsl(231, 48%, 48%)',
'label': 'Indigo'
},
{
'color': 'hsl(207, 90%, 54%)',
'label': 'Blue'
},
]
definujem farby palety

Krok 5
Úprava modelu
from django_ckeditor_5.fields import CKEditor5Field
class Article(models.Model):
VISIBILITY_CHOICES = [
('public', 'Verejný'),
('private', 'Súkromný'),
]
title = models.CharField(max_length=200, verbose_name="Názov článku")
short_description = models.CharField(max_length=500, verbose_name="Krátky popis", blank=True, null=True)
content = CKEditor5Field(config_name="extends", verbose_name="Obsah článku")
created_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to=article_image_upload_path, verbose_name="Obrázok", blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Kategória")
is_deleted = models.BooleanField(default=False, verbose_name="Vymazaný")
visibility = models.CharField(
max_length=10,
choices=VISIBILITY_CHOICES,
default='public',
verbose_name="Viditeľnosť"
)
def __str__(self):
return f"{self.title} ({'Vymazaný' if self.is_deleted else 'Aktívny'}) {self.short_description}"
Krok 6
Migrácie a spustenie servera
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Krok 7
Využitie CKEditor v admin alebo vlastnom formulári
# ========================================
# Formulár pre pridávanie a úpravu článkov
# ========================================
# Nacitanie kniznic pouzitych pre formular
from django_ckeditor_5.widgets import CKEditor5Widget
from peter_pekny_page.models import Article
from peter_pekny_page.models import Category
class ArticleForm(forms.ModelForm):
"""Formulár pre pridávanie a úpravu článkov."""
# Definujeme category tu, kvoli rozsirenym moznostial objektu
category = forms.ModelChoiceField(
queryset=Category.objects.all(), # Načítame dostupné kategórie
required=True, # Pole je povinné
empty_label="Vyberte kategóriu", # Používateľ musí niečo vybrať
widget=forms.Select(attrs={'class': 'custom-select'}) # Štýlovanie selectu
)
class Meta:
model = Article
fields = ['title', 'short_description', 'content', 'visibility' , 'category']
widgets = {
'short_description': forms.Textarea(attrs={
'class': 'styled-input',
'rows': 3,
'placeholder': 'Zadajte krátky popis článku...',
}),
'content': CKEditor5Widget(config_name='extends'),
'visibility': forms.Select(choices=Article.VISIBILITY_CHOICES, attrs={'class': 'custom-select'}),
# 'category': forms.Select(attrs={'class': 'custom-select'}), # Nepotrebujeme, pretože je definované vyššie - obmedzene moznosti widgetu - prebera info len s Modelu
}
# ========================================
# Formulár pre pridávanie komentárov
# ========================================
# Nacitanie kniznic pouzitych pre formularov
from .models import Comment
class CommentForm(forms.ModelForm):
"""Form for comments to the article."""
class Meta:
model = Comment
fields = ['comment']
widgets = {
"comment": CKEditor5Widget(
config_name='comment',
attrs={
# "style": "min-height: 130px !important;", # Obmedzenie výšky na približne 5 riadkov
"placeholder": "Zadajte komentár..." # Predvolený text
}
)
}
Týmto spôsobom bude CKEditor5 dostupný ako editor pre textové pole vo formulári, čím umožní pohodlnú a vizuálnu úpravu obsahu.
Komentáre ku článku
Zatiaľ žiadne komentáre.