Django Admin CKEditor

CKEditor is an open source WYSIWYG text editor designed to bring common word processor features directly to web pages, simplifying their content creation. Its core code is written in JavaScript. In this article we going to use basic CKEditor in django application.

Lets consider a table called Article,

models.py

from django.db import models

class Article(models.Model):
	title 		= 	models.CharField(max_length=128)
	content 	= 	models.TextField()

	def __str__(self):
		return self.title

Register the model to django admin,

admin.py

from django.contrib import admin

from editor.models import Article

admin.site.register(Article)

The model form will be looking like this in the django admin page,

Here we going to change the content TextField to CKEditor.

Now create a directory called static and add that path in the settings.py file,

settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

Now download the CKEditor from here. Here I used Basic Package of CKEditor. After downloading it, extract  the ckeditor into the static directory.

Now create a directory called js inside static directory and create a file called custom.js and add these lines,

custom.js

$( document ).ready(function() {
    CKEDITOR.replace( 'id_content'); //Here the 'id_content' is the reference of the 'content' field in the model
});

Now create a directory called css inside static directory and create a file called custom.css and add these lines,

custom.css

.aligned label {
  	float:none;
}

Finally download the JQuery file from here and put it into js directory and the static folder structure looks like this,

static
	├── ckeditor
	├── css
	│   └── custom.css
	└── js
	    ├── custom.js
	    └── jquery-2.2.4.min.js

And here comes the tricky part, Django admin has the Media class to define static files(js, css) for a particular model instance, now modify the admin.py like this,

admin.py

from django.contrib import admin

from editor.models import Article

class ArticleAdmin(admin.ModelAdmin):
	class Media:
		js = (
			'/static/js/jquery-2.2.4.min.js',
			'/static/ckeditor/ckeditor.js',
			'/static/js/custom.js',
		)
		css = {
            'all': ('/static/css/custom.css',)
        }

admin.site.register(Article, ArticleAdmin)

That's it and now we can enjoy the CKEditor, now the model form will be looking like this in the django admin page with CKEditor for the content field.

You will find the source code here.

I hope you enjoyed this article, if you face any issues or problem, please feel free to give your feedbacks in the comment secton.

  • Django
  • Django-Admin
  • CKEditor