Tinymce Editor

Installation

pip install django-tinymce
   INSTALLED_APPS = [
     #...
    'myapp',
    'tinymce',
    ]
    
TINYMCE_DEFAULT_CONFIG = {
    'height': 400,
    'width': 800,
    'plugins': '''
        advlist autolink lists link image charmap print preview hr anchor pagebreak
        searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime
        media nonbreaking save table contextmenu directionality emoticons template paste
        textcolor codesample toc noneditable quickbars
    ''',
    'toolbar': '''
        undo redo | formatselect | bold italic underline strikethrough | forecolor backcolor
        alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | 
        link image media | table | blockquote codesample | charmap emoticons | quickbars
    ''',
    'contextmenu': 'formats | link image',
    'content_css': [
        # Add your own content CSS files here
    ],
    'codesample_languages': [
        { 'text': 'HTML/XML', 'value': 'markup' },
        { 'text': 'JavaScript', 'value': 'javascript' },
        { 'text': 'CSS', 'value': 'css' },
        { 'text': 'Python', 'value': 'python' },
        { 'text': 'Java', 'value': 'java' },
        { 'text': 'Ruby', 'value': 'ruby' },
        { 'text': 'PHP', 'value': 'php' }
        # Add more languages if needed
    ],
    'init_instance_callback': 'tinymce_init_callback'
}

def tinymce_init_callback(editor):
    editor.settings['setup'] = 'function(editor) { ' \
                               'editor.on("init", function() { ' \
                               'editor.getDoc().querySelectorAll("pre code").forEach(function(block) { ' \
                               'hljs.highlightBlock(block); ' \
                               '}); ' \
                               '}); ' \
                               '}'

Setup Tinymce With Model

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
## Add This Line
from tinymce.models import HTMLField


class Post(models.Model):
    title = models.CharField(max_length=120)
    content = HTMLField() # Change This Line
    published_at = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Change Html Tempalte Tag

<body>
    <h1>My Posts</h1>
	{% for post in posts %}
		<h2>{{ post.title }}</h2>
		<small>Published on {{ post.published_at | date:"M d, Y" }} by {{ post.author | title}}</small>

		<p>{{ post.content|safe }}</p> <!-- Change This Line -->
	{% endfor %}
</body>

Last updated