Add text editor TinyMCE in Django Python
2 min readMar 12, 2024
Create model in models.py, these codes:
Install Django TinyMCE: Start by installing django-tinymce
using pip:
pip install django-tinymce #terminal or vscode
Configure Django Settings: Add 'tinymce'
to your INSTALLED_APPS
in your Django project's settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'tinymce', #add tinymce
]
Configure TinyMCE Settings: Create a configuration file for TinyMCE if you need to customize its behavior. Exampke code.
// tinymce_config.js
tinymce.init({
selector: 'textarea',
height: 500,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar: 'undo redo | formatselect | ' +
'bold italic backcolor | alignleft aligncenter ' +
'alignright alignjustify | bullist numlist outdent indent | ' +
'removeformat | help'
});
Edit forms.py
from tinymce.widgets import TinyMCE
class PostNewsForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
class Meta:
model = PostNews
fields = '__all__'
Add TinyMCE in admin.py
from tinymce.widgets import TinyMCE
from django.db import models # required for TinyMCE
class PostNewsAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'created_at', 'category')
search_fields = ('title', 'author__username', 'category')
list_filter = ('created_at', 'category')
date_hierarchy = 'created_at'
readonly_fields = ('created_at',)
# Menentukan TinyMCE untuk field content
formfield_overrides = {
models.TextField: {'widget': TinyMCE()}
}
Run Migrations: If you have made changes to your models, remember to run migrations:
python manage.py makemigrations
python manage.py migrate
OR
Add
in yout project templates
{{ news.content|safe|linebreaks }}
My Instagram @andiihermanto