Want to use a WYSIWYG editor within your Django webapp? TinyMCE is a good choice and the best: there is a Django module that makes the implementation as easy as pie.
When I programmed the backend of this this blog website, I decided to include a WYSIWYG editor for the content area of the blog articles.
Generally, I don't like WYSIWYG editors very much, but since I wanted to show examples of source code, I found this tool very helpful. After a short market research I decided to use TinyMCE. The good thing about TinyMCE, regardless of the numerous configuration options and plug-ins, is the fact that there is a Django package.
First download the community edition of TinyMCE: https://www.tinymce.com/download/ and the language package of your choice: https://www.tinymce.com/download/language-packages/ and put it in your "static" folder.
Then install the Django package.
$ pip install django-tinymce
Add the package to INSTALLED_APPS in your settings.py
INSTALLED_APPS = (
...
'tinymce',
...
)
Now, configure TinyMCE in your settings.py. Here is an example of my configuration.
TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tinymce/tinymce.min.js")
TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "js/tinymce")
TINYMCE_DEFAULT_CONFIG = {
'height' : 300,
'plugins': "image,imagetools,media,codesample,link,code",
'cleanup_on_startup': True,
'menubar': False,
'toolbar': "styleselect |undo redo | bold italic | alignleft aligncenter alignright | link image media codesample code",
'image_caption': True,
'image_advtab': True,
'custom_undo_redo_levels': 10,
'file_browser_callback' : "myFileBrowser"
}
The result of the above configuration looks like the following:
Enable TinyMCE in your forms.py where you want it to be shown.
from tinymce.widgets import TinyMCE
.
.
.
class PostForm(forms.ModelForm):
text = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows':50,'class': 'form-control'}))
To get the file browser button working, I had to put in the JavaScript function I configured in settings.py ('file_browser_callback' : "myFileBrowser") into the regarding template file:
function myFileBrowser (field_name, url, type, win) {
var cmsURL = '{% url 'media_list_editor' %}';
if (cmsURL.indexOf("?") < 0) {
cmsURL = cmsURL + "?type=" + type;
}
else {
cmsURL = cmsURL + "&type=" + type;
}
tinyMCE.activeEditor.windowManager.open({
file : cmsURL,
title : 'Bilddatenbank',
width : 800,
height : 600,
resizable : "yes",
inline : "yes",
close_previous : "no"
}, {
window : win,
input : field_name
});
return false;
}
Now I had a working WYSIWYG editor in my Django application.
Cover image by Luis Gomes | blur-close-up-code-computer-546819 | CC0 License