Last modified: May 08, 2021

Django-CKEditor: Integrate and Upload Images Easily

In this tutorial, we'll learn how to install and set up Django-CKEditor, where you will be able to upload photos easily with content.

So let's get started.

Install Django-CKEditor

Install via pip:

pip install django-ckeditor

In settings.py, add 'ckeditor' and 'ckeditor_uploader' to your INSTALLED_APPS.


# Application definition

INSTALLED_APPS = [
    ...
    #libs
    'ckeditor',
    'ckeditor_uploader',
    #Apps
    ...
]

Also in settings.py, set STATIC_URL, MEDIA_URL, and CKEDITOR_UPLOAD_PATH.


STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

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

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_UPLOAD_PATH: Image upload path.

Note: in MEDIA_URL, you must add the first slash / because, without it, the images will not appear.

In urls.py, you need to add some lines:


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

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

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Now, let's create a model to see how the editor looks like?

In models.py:


from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField

class Topic(models.Model):
    title = models.CharField(max_length=100)
    content = RichTextUploadingField()
    def __str__(self):
        return self.title

RichTextUploadingField: The editor's field.

To represent our model in the admin interface, add this line in admin.py.


from django.contrib import admin

#models
from .models import *

admin.site.register(Topic)


Django-CKEditor in Admin interface:

image-1

How to upload image with Django-CKEditor

To upload images, you need to follow these sequence of images:

1:

Django-CKEditor: integrate and upload image an essay way

2:

Django-CKEditor: integrate and upload image an essay way

3:

Django-CKEditor: integrate and upload image an essay way

4:

Django-CKEditor: integrate and upload image an essay way

5:

Django-CKEditor: integrate and upload image an essay way

6:

Django-CKEditor: integrate and upload image an essay way

Display content of editor on the template

To display the editor's content on an HTML page you need to do something like:


<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>

     {{obj.content|safe}}

   </body>
</html>


for more information:

https://github.com/django-ckeditor/django-ckeditor