Showing posts with label ckeditor. Show all posts
Showing posts with label ckeditor. Show all posts

Adding CKEditor to Django Admin

This article will show how to enhance the django admin site's textareas by replacing them with the CKEditor control.

Install CKEditor

Download the CKEditor here. Place the CKEditor source in such a spot that the static web server can serve it. In my case I have created a media directory under the document root of the web static web server and then placed the CKEditor files in a directory ckeditor. Thus I can access the ckeditor.js like this http://localhost/media/ckeditor/ckeditor.js.

Update the MEDIA_URL = 'http://localhost/media/'  in the settings.py of your django project.

My sample model is very simple and looks like this:
from django.db import models

class SampleModel(models.Model):
  title = models.CharField(max_length=50)
  text = models.TextField()

  def __unicode__(self):
    return self.title

The magic happens in the custom model admin form. The for for my sample model looks like this:

from sampleapp.models import SampleModel
from django.contrib import admin
from django import forms
from django.db import models

class SampleModelAdmin(admin.ModelAdmin):
  formfield_overrides = { models.TextField: {'widget': forms.Textarea(attrs={'class':'ckeditor'})}, }

  class Media:
    js = ('ckeditor/ckeditor.js',) # The , at the end of this list IS important.
       
admin.site.register(SampleModel,SampleModelAdmin)
The important things to notice is that I add class attribute to the textarea widget. When ckeditor then satrt up it knows to replace any textareas with the ckeditor code.

The last thing to notice is the the media location is relative to the MEDIA_URL since there is no preceding /.

That's it. 


Her is the sample application: django-ckeditor.zip. Or you can get is directly from the subversion repository:

svn checkout http://johanscode.googlecode.com/svn/devblog/django/ckeditor johanscode-read-only