How to use ckeditor in Django project with images and code snippet

Jan. 8, 2023


0
4 min read
963

CKEditor is a rich text editor that gives us a lot of options to customize our text. In this article, how will we use CKEditor with our project To use CKEditor in Django, you will need to install django-ckeditor and add it to your Django project. 

Click here to know the features of CKEditor

Install the django-ckeditor package by running the following command:

pip install django-ckeditor

Add ckeditor to the INSTALLED_APPS list in your Django settings.py file:

INSTALLED_APPS = [
    "channels",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "blogs_app",

    "ckeditor",  # new
    "ckeditor_uploader",  # new
]

 Include the CKEditor URL patterns in your Django urls.py file:

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("blog_app.urls")),
    path("ckeditor/", include("ckeditor_uploader.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You have to create your own models in models.py:

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

class Blog(models.Model):
    title = models.CharField(max_length=300)
    content = RichTextUploadingField(null=True, blank=True)

    def __str__(self):
        return self.title

If you want to do it in frontend then you can create forms in forms.py:

from django import forms
from .models import Blog


class BlogForm(forms.ModelForm):
    class Meta:
        model = Blog
        fields = ['title', 'content']

Before rendering the CKEditor you have to give the media path in settings.py and make some changes to make it responsive

# media path
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_UPLOAD_PATH = "uploads/"

# for responsive & code snippet
CKEDITOR_CONFIGS = {
    "default": {
        "toolbar": None,
        "width": "100%",
        "extraPlugins": ",".join(
            [
                "codesnippet",
            ]
        ),
    },
}

Run the following command to apply the migrations:

python manage.py makemigrations

python manage.py migrate

You can then render the form in your template. Your view should be something like this:

from django.shortcuts import render
from .forms import BlogForm


def add_blog(request):
    if request.method == "POST":
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    form = BlogForm()
    return render(request, "forms.html", {"form": form})

Your forms.html template should be something like this:

{% include "base.html" %}
{% block forms %}
<form method="post" >
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form> 
{% endblock forms %}

You need to add this script tag in your base.html template for the code snippet

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documents</title>
</head>
<body>
    {% block forms %}
      
    {% endblock forms %}
    {% block content %}
      
    {% endblock content %}
    {% block ckeditor %}

<link rel="stylesheet" href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/monokai.css' %}" />
<script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script>

<script>hljs.initHighlightingOnLoad();</script>

{% endblock ckeditor %}
</body>
</html>

To show data your view should be like this:

from .models import Blog

def home(request):
    data = Blog.objects.all()
    return render(request, "blod_details.html", {"data": data})

As we already know, by default, Django escapes HTML because of security concerns. We can tell Django not to escape data by using safe the filter. Open blog_details.html in the blog directory and change dt.content to dt.content|safe.

{% include "base.html" %}
{% block content %}
  {% for dt in data %}
    <h1>{{dt.title}}</h1>
    <p>{{dt.content|safe}}</p> <br>
  {% endfor %}
{% endblock content %}

And your blog_app URLs should be something like this:

from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
    path("add-blog/", views.add_blog, name="add-blog"),
]

You can see the screenshot here👇

I hope this helps! If you want to learn Django, we are bringing a course for that, you can see it by clicking here Django Beginner to Advanced course

django projects coding ckeditor Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.