How to Add a CkEditor in Django Model

Posted: September 11, 2024 | Updated: October 06, 2024

CKEditor is one of the popular mostly used WYSIWYG (What You See Is What You Get) editors. You can easily integrate CKEditor on your Django site.

How to Add a CkEditor in your Django Site

Step 1: Install the CKEditor in Django

First, install ckeditor in django using the pip command. 

pip install django-ckeditor

Step 2: Add the CKEditor in your App Setting.py file

Then,  Add  the 'ckeditor' to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    'ckeditor',
    'ckeditor_uploader',
]

CKEDITOR_UPLOAD_PATH = "uploads/"

If you need full CK editor tools, add these additional lines in your settings.py file.

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'full',
    },
}

Step 3: Add CKEditor RichTextField in your Django Model

In your models.py, import and use the RichTextField from ckeditor.fields:

from django.db import models
from ckeditor.fields import RichTextField

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = RichTextField(blank=True, null=True)

    def __str__(self):
        return self.title

Step 4: Migrate the Changes

Use the following commands to migrate the changes to the database.

python manage.py makemigrations
python manage.py migrate

Step 5: Display the CKEditor content in your HTML template

If you using CKEditor content on your HTML template, add the "|safe" to escape the HTML tags.

 {{post.content|safe}}

That's all.

© 2024 Webapptiv. All rights reserved.