Adding a rich-text editor for WYSIWYG editing

Sometimes, you will need to include JavaScript code in the admin interface. A common requirement is to use an HTML editor, such as CKEditor, for your TextField.

There are several ways to implement this in Django, for example, using a Media inner class on your ModelAdmin class. However, I find extending the admin change_form template to be the most convenient approach.

For example, if you have an app called posts, then you will need to create a file called change_form.html within the templates/admin/posts/ directory. If you need to show CKEditor (it could be any JavaScript editor, but this one is the one I prefer) for the message field of a model in this app, then the contents of the file can be as follows:

{% extends "admin/change_form.html" %} 
 
{% block footer %} 
  {{ block.super }} 
  <script src="//cdn.ckeditor.com/4.4.4/standard/ckeditor.js"></script> 
  <script> 
   CKEDITOR.replace("id_message", { 
     toolbar: [ 
     [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList'],], 
     width: 600, 
   }); 
  </script> 
  <style type="text/css"> 
   .cke { clear: both; } 
  </style> 
{% endblock %} 

The part in bold is the automatically created ID for the form element we wish to enhance from a normal textbox to a rich-text editor. This change will not affect other textboxes or form fields in the admin site. These scripts and styles have been added to the footer block so that the form elements are created in the DOM before they are changed.

Other approaches for achieving this might require the installation of apps and other configuration changes. For changing just one admin site field, this might be overkill. The approach here also gives you the flexibility to pick and choose the JavaScript editor of your choice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.239