Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. CKEditor

CKEditor

Step 1: Install django-ckeditor-5

First, install the package using pip:

pip install django-ckeditor-5

Step 2: Update Django Settings

Open your settings.py file and make the following updates:

  1. Add ckeditor and ckeditor_uploader to INSTALLED_APPS:
INSTALLED_APPS = [
    # Other installed apps...
    'django_ckeditor_5',
]

Configure CKEditor settings:

Add the following settings in settings.py:

# CKEditor 5 File Storage Setup
CKEDITOR_5_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"  # Default file system storage
# CKEditor 5 File Upload Path
CKEDITOR_5_UPLOAD_PATH = "uploads/"  
# Custom Color Palette for Tables and Background
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'
    },
    {
        'color': 'hsl(120, 75%, 60%)',
        'label': 'Green'
    },
    {
        'color': 'hsl(60, 90%, 50%)',
        'label': 'Yellow'
    }
]

# CKEditor 5 Configuration
CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': [
            'heading', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'subscript', 'superscript', 'highlight', 
            '|', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'insertTable', 'imageUpload', '|',
            'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', '|',
            'codeBlock', 'sourceEditing', 'outdent', 'indent'
        ],
        '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': customColorPalette,
                'backgroundColors': customColorPalette
            },
            'tableCellProperties': {
                'borderColors': customColorPalette,
                'backgroundColors': customColorPalette
            }
        },
        'list': {
            'properties': {
                'styles': True,  # Allows list styles (e.g., circle, disc, square)
                'startIndex': True,  # Allows lists to start at a specific number
                'reversed': True  # Allows numbered lists to be reversed
            }
        },
        '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'}
            ]
        },
        'mediaEmbed': {
            'previewsInData': True  # Enable media preview in the editor
        },
        'height': 500,  # Editor height
        'width': '100%',  # Editor width
    }
}


# Media Configuration
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Step 3: Update Your Model

Update your Notice model to use RichTextUploadingField:

from django.db import models
from django_ckeditor_5.fields import CKEditor5Field
from django.contrib.auth import get_user_model

class Notice(models.Model):
    TARGET_CHOICES = [
        ('ALL', 'All Departments'),
        ('DEPT', 'Specific Departments'),
        ('USER', 'Specific Users'),
    ]

    title = models.CharField(max_length=255)
    content = CKEditor5Field('Content')  

Step 4: Create a Custom Form

Create a custom form for your Notice model to use the CKEditorWidget. You can do this in forms.py:

from django import forms
from .models import Notice    
from django_ckeditor_5.widgets import CKEditor5Widget  
class NoticeForm(forms.ModelForm):
    class Meta:
        model = Notice
        fields = ['title', 'content', 'department', 'user', 'target_type','file']
        widgets = {
            'content': CKEditor5Widget(config_name='default'), 
        }

Step 5: Update the Admin Configuration

Modify your admin.py to use the custom form for the NoticeAdmin class:

from django.contrib import admin
from .models import Notice
from .forms import NoticeForm

@admin.register(Notice)
class NoticeAdmin(admin.ModelAdmin):
    list_display = ('title', )
    form = NoticeForm  # Use the custom form

Step 6: Configure URLs

Ensure your urls.py is set to serve the CKEditor file uploads. Add the following:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

urlpatterns = [
    # Other URL patterns...
    path('ckeditor5/', include('django_ckeditor_5.urls')),  # Include CKEditor 5 URLs
] 
# Serve media files during development
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Run Migrations

After making changes to your models, run the following commands to apply migrations:

python manage.py makemigrations
python manage.py migrate

How can we help?