How to use CKEditor in Django?

In this Python Django tutorial, we will understand how to integrate a rich text editor into our Django project. And in this tutorial, we will explain how to use the CKEditor in Django.

Moreover, we will also see the steps to integrate the CKEditor into the Django Admin and Django Forms using examples.

First, let us understand what is a rich text editor.

Introduction to Rich Text Editor

A rich text editor is a tool that allows users to create and edit formatted documents. Typically a rich text editor includes various tools for styling text, such as bold, italic, and underline, as well as for creating lists, tables, and links.

Some rich text editors also support the insertion of multimedia elements, such as images and videos. Here is the list of some well-known rich text editors available for Django.

  • TinyMCE
  • CKEditor
  • Quill
  • Summernote
  • Froala Editor
  • Redactor

In this Python tutorial, we will discuss how to use the CKEditor as a rich text editor in our Django project.

This Django project will focus on creating a simple blog post website. And for posting blog content, we will use the CKEditor in Django. Here are the steps that we can follow for this Django project.

If you have not installed see: How to install Django

Step 1: Create & activate a virtual environment for Django Project

In the first step, we will create a virtual environment for our Django project. And for this, we will use the following command in CMD.

> python -m venv myblogs-env

Here we created a virtual environment named myblogs-env.

Once the virtual environment is created, we will use the following command to activate it.

> myblogs-env\Scripts\activate

With this, we have successfully created and activated a virtual environment using Python.

Step-2: Installing Django & CKEditor in Django

Next, we will install the Django framework using the following pip command.

Note: Please make sure you run the command with the activated virtual environment.

> pip install django

After Django, the next dependency is CKEditor. However, to add the functionality of CKEditor, we need to the django-ckeditor module using the following command.

> pip install django-ckeditor

Read: Python Change Django Version

Step 3: Setup a Django Project

After installing the dependency, next, we will follow the following steps to set up the overall Django project.

Creating Django Project

First, we will create a Django project using the following command.

> django-admin startproject MyBlogs

Here we created the Django project with MyBlogs as the project name. This will create the MyBlogs directory will also the project files.

READ:  Scipy Ndimage Rotate

Moving to the project directory

Once the project directory is created, we will move to the project directory using the cd command.

> cd MyBlogs

Creating Django App

Inside the project directory, we will create our Django App using the startapp command.

> python manage.py startapp myapp

Here we created the Django app named myapp. And once the command is executed successfully, it will automatically generate all the application files under the myapp directory.

Open the Django Project in the VSCode

Start Visual Studio Code > Under Get Started click on the Open Folder option > Select the myBlogs directory.

Configure Apps under INSTALLED_APPS

Next, open the settings.py from myBlogs directory and add the myapp application and ckeditor under the INSTALLED_APPS list.

INSTALLED_APPS = [
    .
    .

    .
    'myapp',
    'ckeditor',
]

Basic URL configuration

Django by default provides a urls.py file to map the newly created app inside of it in the project directory. Add the code below to it to do this.

from django.contrib import admin
from django.urls import path, include

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

Till now, this step, we have successfully completed the basic Django project configuration.

Read: Python Django format date

Step 4: Creating Django Model

To store data for our blogs, we will create a model. However, we can define models under the models.py file for each application.

So, open myapp/models.py and add the following Python code.

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

class BlogPost(models.Model):
    blog_title = models.CharField(max_length=200)
    blog_content = RichTextField()
    publish_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.blog_title

Here we created a model named BlogsPost using the models.Model class. This consists of the following 3 fields.

  • blog_title: It is a character field used to store the title of the blog. Also, its maximum length is 200 characters.
  • blog_content: This will be the rich text editor field. For this, we used RichTextField() from ckeditor.fields.
  • publish_date: This is a DateTime field whose value will automatically fill on submission.

In the last, we specified the display name for each record as the blog title itself.

Step 5: Register the model on the admin site

Next, we will register the BlogsPost model on the admin site so that we can access the model on the Django Admin Panel.

For this task, open the admin.py file under the myapp directory and add the following code.

from django.contrib import admin
from .models import BlogPost

admin.site.register(BlogPost)

Read: Python Django vs ReactJS

Step 6: Creating a form using the Django model

Next, we will create a Django Form using the same fields defined in the myBlogs model. For this execution simply add the following code in the myapp/forms.py file.

Note: Please note that if forms.py file is not available, please create it in your application directory.

from django import forms
from .models import BlogPost


class BlogPostForm(forms.ModelForm):

    class Meta:
        model = BlogPost
        fields = ('blog_title', 'blog_content')
        exclude = ['published_date']

Step 7: Rendering the Django ModelForm in Templates

Once we create a form, we can render the form in our templates. For this, follow the following steps:

READ:  Python Tkinter to Display Data in Textboxes

First, create a templates directory in your application directory (under myapp).

Next, open the settings.py file and include the templates directory under the DIRS key list.

TEMPLATES = [
    {
        .
        'DIRS': ['templates'],
        .
        'OPTIONS': {
            'context_processors': [
                .,
                .,
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

After this, create another file named home.html under the templates directory. And then add the following Python code.

<!DOCTYPE html>
<html lang="en">
<head>
    <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> My Blog Post</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}

        <input type="submit" value="Submit">
    </form>
</body>
</html>

In the HTML page, we are loading the forms that we created earlier using the models.

Read: How to Create model in Django

Step 8: Creating views and storing data to model

Next, we need to define the logic to fetch the data from the Django Form and store it in the BlogPost model.

For this task, we create a function-based view in the views.py file of the myapp directory. Here is the Python code for the views.py file.

from django.shortcuts import render
from django.http import HttpResponse
from .forms import BlogPostForm

def create_blog_post(request):
    if request.method == 'POST':
        form = BlogPostForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('New Blog Successfully Added')
    else:
        form = BlogPostForm()
        context = {
            'form':form
        }

    return render(request, 'home.html', context)

Here we defined a function-based view named create_blog_post. This view will check if the form is valid or not. And if the form is validated successfully, it will store the form data in the tables.

However, if the form is not fully validated, it will again return the form.

Step 9: Defining the URL for the view

Next, we just need to map the view to an URL and for this, we open the myapp/urls.py file and add the following code.

from django.urls import path
from .views import create_blog_post

urlpatterns = [
    path('', create_blog_post, name='create_blog_post')
]

Step 10: Make Migrations

Because we have created a model to store the blog data, it is important to run migrations so that changes could be reflected in our table.

> python manage.py makemigrations
> python manage.py migrate

Step 11: Creating a superuser in Django

Once our migrations are completed, we need to create a superuser to access the Django Admin Panel. For this, use the below command.

> python manage.py createsuperuser

After executing the command, it will ask superuser name, email, password, and confirm password.

Also, check: Python Django get admin password

Step 12: Run the development server

Now, we are ready to access our application, for this use the following command in the command prompt.

> python manage.py runserver

Once we successfully, run the above command, it will start the lightweight Django development server at 8000 port by default. To access the Django project, open this http://127.0.0.1:8000/ URL in the browser.

The result of this page is shown below.

Form without ckeditor in django
Form without CKEditor in Django

On the page, we can see the rich text editor is not added for the Blog content field.

Next, open the http://127.0.0.1:8000/admin/ URL, and use the superuser credentials to log in to the Django Admin Interface.

Here if we open the Blog posts given under the MYAPP section and click on Add Blog Post, we can observe the rich text editor is added for the Blog content field.

ckeditor in django admin
Using CKEditor in Django Admin

However, to add the CKEditor to our forms, we need to add the following code to the HTML file. Here HTML file refers to home.html

<form method="post">
        {% csrf_token %}
        {{form.as_p}}
        {{form.media}}
        <input type="submit" value="Submit">
    </form>

After adding the above code, refresh the http://127.0.0.1:8000/ page and now, we will get the CKEditor for the Blog content form field. Here is the result.

ckeditor in django form
Adding CKEditor in Django form

Now, we can use this CKEditor to add data in a document format containing different text properties, bold, italic, underline, etc. It also allows to insert tables and even images into the same document.

READ:  Write a Program to Find the Area of a Rectangle in Python

Here is an example:

using ckeditor in django form
Using CKEditor in Django Form

Read: Python Django MySQL CRUD

Rendering CKEditor Data in HTML Template

Till now, we have successfully integrated the CKEditor in Django form and Django Admin Interface. Next, we need to understand how to load or render the data stored using CKEditor in our HTML template.

For this task, we will create 2 more views in our views.py file.

  1. blog_list: This view will list all the blog names that are there in the BlogPost model
  2. blog_view: This view will allow viewing the exact content of the particular blog.

The code for both views is given below.

def blog_list(request):
    blog_list = BlogPost.objects.all()
    return render(request, 'blog_list.html', {'blogs': blog_list})

def blog_view(request,blog_id):
    blog_view = BlogPost.objects.filter(id=blog_id)
    return render(request, 'blog_view.html', {'blog': blog_view})

Now, in each view, we can see the blog_list view is redirecting to the blog_list.html page. And the blog_view view is redirecting to the blog_view.html page.

First, let us look at the code of the blog_list.html page.

<body>
    <h1>List of Blogs</h1>
    <ol>
        {% for blog in blogs %}
        <li><a href="{% url 'blog_view' blog_id=blog.id %}">{{ blog.blog_title }}</a></li>
        {% endfor %}
    </ol>
</body>

Here we are using for loop to get all the blog titles as a list and then we are converting the title into links. This URL link will redirect to the particular blog page.

After this, let us look at the blog_view.html page.

<head>

    {% for info in blog %}
    <title>{{info.blog_title}}</title>
</head>
<body>
    <h1 style="text-align: center;"><u>{{info.blog_title}}</u></h1>
    {{info.blog_content | safe}}
    {% endfor %}
</body>

On this page, we are also using for loop to fetch the title and content of the blog. However, as the blog_content field also consists of HTML tags, we need to use the safe flag with it.

Once, both the HTML files are set, we just need to define the URL for each view in Django. For this task, we will add the following code to the urls.py file of our Django App.

from django.urls import path
from .views import create_blog_post, blog_list, blog_view

urlpatterns = [
    path('', create_blog_post, name='create_blog_post'),
    path('blogs/', blog_list, name='blog_list'),
    path('blogs/<int:blog_id>', blog_view, name='blog_view'),
]

Now, run the development server using runserver command and open the http://127.0.0.1:8000/blogs/ URL in your browser.

Here all the Blog names will be listed

ckeditor in django example
Listing all the Blog Titles

Now, if we click on any of the links, it will open the blog_view page containing the blog data.

Blog application in Django
CKEditor in Django

You may also like to read the following Python Django tutorials.

Conclusion

So, in this Python Django tutorial, we understood how to integrate a rich text editor into our Django Project. Here we understood how to integrate and use the CKEditor in Django.

In addition to this, we also understood how to render the data stored using the CKEditor in Django Template.