How to add rich text box editor in django admin

In this article, we are going to see how we can implement a rich text box editor in our Django admin side in TextField.By using this tool we can easily give a better format to our content. 



So let's start working on it, first of all, we have to install a plugin for it.

> pip install django-summernote

Once your plugin installation has been done, then register it in your installed app in the settings.py file. Just add the plugin in your INSTALLED_APPS as I have added in the given code.

yourapplication/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'questions',
    'django_summernote',
]
After this, you have to add a TextField in your models where you to add this tool. So here I'm creating a model which will contain a TextField.

yourapp/models.py
class Questions(models.Model):
    CHOICE = (
        ('','-----------'),
        ('mcq','MCQ'),
        ('practice','Practice'),
    )
    type = models.CharField(max_length=255,choices=CHOICE,default='')
    title = models.CharField(max_length=255,null=False)
    description = models.TextField(null=True,blank=True)
    subject = models.CharField(max_length=255, blank=True, null=True)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.title
    
So this is my model class, Here I will try to implement a rich text box tool on my description field. For that, we have to do small customization in our admin pannel. So let's open the admin.py of your app and add the given code in your admin.py

yourapp/admin.py 
from django.contrib import admin
from .models import Questions
from django_summernote.widgets import SummernoteWidget
from django.db import models

# Register your models here.
class QuestionAdmin(admin.ModelAdmin):

    formfield_overrides = {
        models.TextField: {'widget': SummernoteWidget},
    }
    
admin.site.register(Questions,QuestionAdmin)

Once everything is done, then first do the migration and run your server.
> python manage.py makemigrations
> python manage.py migrate
> python manage.py runserver
If you are getting any issues kindly let me know in the comments.

Happy Coding...

Comments