How to use Rich Text Field in Django?

Published On: 20/01/2023 | Category: Django


Hi Dev,

Now, let's see article of how to use rich text field in django. In this article, we will implement a how to use rich text editor in django. let’s discuss about django rich text field editor example. I explained simply step by step django create rich text field in model example. So, let's follow few step to create example of django-ckeditor example.

We will use the CK editor fields as Rich Text Field in Django. The CK editor is an external package for Django. This package will allow the addition of Custom fields in Django projects.

Here i will give you we will help you to give example of how to use rich text field in django. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject mypro

Step 2: Create an App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

cd mypro
django-admin startapp core

Step 3: Install Django-CKEditor Library

First of all we can install the django-ckeditor library. let us see how to use this library.

pip install django-ckeditor

Step 4: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'core', #new
    'ckeditor', #new
]

Step 5: Create a Model

In this step we will require the database model for storing contacts.Open the core/models.py file and add the following code:

core/models.py
from django.db import models
from ckeditor.fields import RichTextField 

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = RichTextField()

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py createsuperuser
python manage.py makemigrations
python manage.py migrate

Step 6: Update the admin.py

In this step, we need to create the views for performing fetch record to the database.Open the core/admin.py file and add:

core/admin.py
from django.contrib import admin
from .models import *

# Register your models here.
admin.site.register(Post)

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/admin address with a web browser.

I Hope It will help you....