Using TinyMCE in Django
When developing a blog website, I decide to use a WYSIWYG editor for write blog articles. After some research, I think TinyMCE is one of the best choices. To use it, we just need to do:
python3 -m pip install django-tinymce4-lite
Now this is an app, so we need to add to our INSTALLED_APPS
in the ../mysite/settings.py
file:
INSTALLED_APPS = (
...
'tinymce',
...
)
Then, add some configuration in the settings.py also:
TINYMCE_DEFAULT_CONFIG = {
'height': 360,
'width': 1120,
'cleanup_on_startup': True,
'custom_undo_redo_levels': 20,
'selector': 'textarea',
'theme': 'modern',
'plugins': '''
textcolor save link image media preview codesample contextmenu
table code lists fullscreen insertdatetime nonbreaking
contextmenu directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak
''',
'toolbar1': '''
fullscreen preview bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
| link image media | codesample |
''',
'toolbar2': '''
visualblocks visualchars |
charmap hr pagebreak nonbreaking anchor | code |
''',
'contextmenu': 'formats | link image',
'menubar': True,
'statusbar': True,
}
Next, we need a pointer to the app so it can be referenced when we call it. Let’s now edit ../mysite/urls.py
urlpatterns = patterns('',
...
path('tinymce/', include('tinymce.urls')),
...
)
Based on the requirement we need one page to write blog articles. So, we need to create forms.py to organize all about form and it can be import to views.py, like this:
from django import forms
from tinymce import TinyMCE
from .models import Postclass TinyMCEWidget(TinyMCE):
def use_required_attribute(self, *args):
return Falseclass PostForm(forms.ModelForm):
content = forms.CharField(
widget=TinyMCEWidget(
attrs={'required': False, 'cols': 30, 'rows': 10}
)
)
class Meta:
model = Post
fields = ('title', 'body', 'content', 'thumbnail',
'categories')
Now, run the server and access website in localhost
Awesome! So this editor allows us to more easily write HTML, insert code snippets, etc.