how to integrate CKEditor in Django

Welcome to my Blog, in this article we learn about how to integrate CKEditor in Django and inside this, we enable the image upload button to add an image in the blog from local. When I add a CKEditor first time in my project then it was very difficult for me but now I can easily implement it in my project so you can learn and implement CKEditor in your project easily.

how to integrate CKEditor in Django

Firstly we create a python environment here is a command to make a environment with Python 3.6.

python3.6 -m virtualenv env

After that we need install Django ckeditor and view the CKEditor Documentation.

Integrate CKEditor in Django

pip install django-ckeditor

This is done we need go to settings file of our project and include the ckeditor.

#settings.py

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

#models.py

class Posts(models.Model):
    title = models.CharField(max_length=200)
    text  = models.TextField()
    created_at = models.DateTimeField(default=datetime.now)

so after this is done we need to go to models so into the models and here we are going to change text field into a rich text field.

#models.py

from ckeditor.fields import RichTextField

class Posts(models.Model):
   title = models.CharField(max_length=200)
   text  = RichTextField()
   created_at = models.DateTimeField(default=datetime.now)

your form will probably look different but you will probably have one of these text field fields and here we don’t need models generic because we are importing from CKEditor fields inside import rich text field now run the server and see that everything is working now but you need to make migrations we are actually preparing changes and that’s cool we have two things have applied here because we are changing models and when you are changing models.

Read More : Django Admin Full Customization step by step

Read More : How Model Queries work in Django

Read More : How to Make Chatbot in Python or Django

so now when we have everything prepared let’s migrate and then changes are applied now let’s start the server.

Now go to admin section and add new posts and there you see have a ckeditor.

ckeditor in django

now we add a new post and there you visit the site so there you go everything works in the backend but in the frontend, the post text description is showing with an HTML tag. we need to change actual templates to remove this raw HTML so that means we need to go to the index template and add a safe with post description ( {{blog.text|safe}} ) again go to the index and refresh the page now you see all HTML tag stuff removed.

add safe in django template
blog content without safe template tag
safe in blog ckeditor
blog content with safe template tag

Image Upload In CKEditor

we are learning how to activate upload image capability in CKEditor in Django admin because right now you don’t have that option see in the screenshot. now go to the admin panel view posts and posts and when you click on the image icon there is no upload option available.

image upload button not enable

let’s go to the settings file and add a CKEditor uploader in installed apps and after that here we need to define a path for the images uploads folder and don’t forget slash.now after we are done here let’s go down there and we are going to define a root for static files and for media files for images.

#settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'post',
    'ckeditor',
    'ckeditor_uploader',
]

CKEDITOR_UPLOAD_PATH = 'uploads/'


STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

so let’s save this stuff and don’t run the server yet there is a lot of things that we need to fix so after this we need to go to project urls.py file and not into individual applications and add a CKEditor upload path and add static root and media root in URLs before adding both media and static firstly we need to import both settings and static when you have done all of the things after that run a collect static command the collect static command collect all of CKEditor files in the static folder see in below:

#urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('post.urls')),
    path('ckeditor',include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

# python manage.py collectstatic

so now we need to go into models and do a little bit of change is there so see this rich text field this must go to rich text uploading field and also here we must include from CKEditor uploader fields import rich text uploading field. so now when we have changed into models we need to do make migrations and then migrate it and we can now run our server for checking everything is fine.

#models.py

from django.db import models
from datetime import datetime
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField


# Create your models here.

class Posts(models.Model):
    title = models.CharField(max_length=200)
    text  = RichTextUploadingField()
    created_at = models.DateTimeField(default=datetime.now)

    def __str__(self):
    	return self.title

Now go back admin and posts and add posts we click on the image icon now you can see the upload images option is activated. so click on the upload tab and choose file now you need to click on ( send it to the server ) and there you go so we had an image and here is many options to adjust an image set dimensions ( height and width ) you can set the border of the image and add HSpace then image takes the same space from left and right side and VSpace then image take same space from top and bottom side and last is alignment here is two options left and right you can align the image left and right of the page.

upload image option enable
upload image option enable in ckeditor in django

now go to admin section and add a new post and here you see top bar of the ckeditor have some options if you want to add more options then go to settings file add a ckeditor configuration.

#settings.py

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': None,
        'extraPlugins': 'codesnippet',
    },
}
how to integrate CKEditor in Django
topbar options
add new options in ckeditor
add new options in topbar ckeditor

Enable ckeditor in template

when you add CKEditor in Django but CKEditor does not enable in Django template but if you want to add blog from the template but right now CKEditor not enable in template now we working on how to enable CKEditor in template now go to our project app and make a forms.py file now we import forms and create a model CkEditorForm form the CkEditorForm name is a class name the class name is a user-defined. Inside the class, we have a class meta and the class takes a model which model you have used and another one is fields. the fields inside have a list to pass a model attribute that you have a view in the template now import the form in the view.py and pass in the template.

#forms.py

from django import forms
from . models import *

class CkEditorForm(forms.ModelForm):
    class Meta:
    	model = Posts
    	fields =['title','text','created_at']

when you pass the form in template then pass {{ckform.text}}. the .text is the field name we have mention in the model and return in the form but now the CKEditor not enable in the template after that add a script tag bottom of the page when all things were done then refresh the page and now you see CKEditor in the template.

<label>Description</label>
<div>{{ckform.text}}</div>

<script type="text/javascript" src="/static/ckeditor/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/static/ckeditor/ckeditor-init.js"></script>
ckeditor add in template
ckeditor in django template

if you liked the article and share it with your friends and if you have any questions about CKEditor in Django feel free to leave me a comment and I will answer the question you have and that’s about it hopefully I will see you again in another article.

Leave a Reply

Your email address will not be published. Required fields are marked *