Embedding CK Editor into Django Blog App

The content fields for the blog posts on this site have been created using a rich text WYSIWYG editor called CK Editor.

This is a JavaScript based editor that can be added to a Django project to give it the ability to add rich text and media to the website.

To implement this, firstly you will need to install the CK Editor. My configuration uses pipenv as the package manager and the installation is being completed within the project's root directory (called src in my case).

Navigate to your project's root directory and spin up a virtual environment using pipenv.

$ pipenv shell

 Install Django CK Editor...

(src) $ pipenv install django-ckeditor

 Then, you will need to register it within your settings area so that Django knows that it is available to your project.

# In settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third Party
    ...
    'ckeditor',  # Add
    'ckeditor_uploader',  # Add
    ...

    # Project Apps
    'myapp.apps.MyappConfig',
    ...
]

Towards the bottom of your project settings, you will need to insert the following code:

# In settings.py
...

CKEDITOR_UPLOAD_PATH = 'uploads/'

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'toolbar_Custom': [
        ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike',
            'SpellChecker', 'Undo', 'Redo'],
        ['Link', 'Unlink', 'Anchor'],
        ['Image', 'Table', 'HorizontalRule'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-',
            'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['TextColor', 'BGColor'],
        ['Smiley', 'SpecialChar'],
        ['RemoveFormat', 'CodeSnippet'],
        ],
        'extraPlugins': 'codesnippet',
    }
}

...

You will need an HTML field within a suitable field within your model. In my case, and perhaps the most canonical example, is a post content field for a blog.

One of the fields within your model will need to be declared as a rich text uploading field so that you can do things like upload images to the field.

# In myapp.models.py

from ckeditor_uploader.fields import RichTextUploadingField


class Post(models.Model):
    ...
    content = RichTextUploadingField()
    ...

You will need to place a reference to the CK Editors in-built urls.py file within your project's urls.py file.

# In your project's urls.py

urlpatterns = [
    ... ,
    path('ckeditor/', include('ckeditor_uploader.urls')),
    ... ,
]

You will then be able to benefit from having rich text at your disposal when you're creating content fields in your application.

If you would like to see the detail for where I learned how to implement this, please check out the video tutorial using the link below.

How to Implement CK Editor into your Django Site