django-tinymce

repository·master·Indexed 23 days ago

https://github.com/jazzband/django-tinymce

A Django application that provides a widget to render form fields as a TinyMCE rich-text editor. It features support for django-staticfiles, integration with django-filebrowser, and the ability to compress TinyMCE Javascript code. The package includes a specialized HTMLField for automatic integration and a TinyMCE widget for custom form definitions, supporting predefined link and image lists for dialogs.

Tokens
3.1K
Snippets
10
Records
14
Agent score
79%

What's inside django-tinymce

  1. Overview of django-tinymce features

    master

    django-tinymce is a Django application that provides a widget to render Django form fields as TinyMCE editors.

    Key features include:

    • Use as a form widget or directly with a view.
    • Enhanced support for content languages.
    • Predefined link and image lists for dialogs.
    • Support for django-staticfiles.
    • Ability to compress TinyMCE Javascript code.
    • Integration with django-filebrowser.

    Starting from version 1.5.1, the TinyMCE editor is bundled with the package to simplify installation and usage.

  2. Configure external link and image lists

    master

    You can enhance TinyMCE's link and image dialogs by providing a predefined list of options via link_list and image_list in mce_attrs. These options must point to a URL that returns a JSON array of objects.

    JSON Format Requirement: Each object in the array must contain title and value fields:

    [
      {"title": "My Page 1", "value": "https://example.com/page1"},
      {"title": "My Page 2", "value": "https://example.com/page2"}
    ]

    Implementation Example:

    To use a predefined link list in a form field:

    from django import forms
    from django.urls import reverse
    from tinymce.widgets import TinyMCE
    
    class SomeForm(forms.Form):
        somefield = forms.CharField(
            widget=TinyMCE(mce_attrs={'link_list': reverse('someviewname')})
        )

    And the corresponding view:

    from django.http import JsonResponse
    
    def someview(request):
        # ... fetch objects ...
        link_list = [{"title": str(obj), "value": obj.get_absolute_url()} for obj in objects]
        return JsonResponse(link_list, safe=False)
    from django import forms
    from django.urls import reverse
    from tinymce.widgets import TinyMCE
    
    class SomeForm(forms.Form):
        somefield = forms.CharField(
            widget=TinyMCE(mce_attrs={'link_list': reverse('someviewname')})
        )
  3. Convert textareas to TinyMCE using the tinymce-js view

    master

    If you cannot modify the form widgets directly, you can use the tinymce-js view to convert textareas on a page into TinyMCE editors via JavaScript.

    1. Add the TinyMCE static file and the tinymce-js script to your template's <head>:

      <script src="{% static 'js/tiny_mce/tiny_mce.js' %}"></script>
      <script src="{% url 'tinymce-js' 'NAME' %}"></script>

      Note: NAME is a placeholder for your configuration name.

    2. Create a JavaScript initialization file in your template path at NAME/tinymce_textareas.js or tinymce/NAME_textareas.js.

    3. Use the tinymce-js-lang view if you need to support a different content language than the interface language:

      <script src="{% url 'tinymce-js-lang' 'NAME','LANG_CODE' %}"></script>
  4. Include TinyMCE media in custom templates

    master

    If you are using TinyMCE in your own templates (outside of the Django admin), you must include the widget's media in the HTML <head> section so the necessary JavaScript files are loaded.

    Assuming your form instance is named form, add {{ form.media }} to your <head>.

    <head>
        ...
        {{ form.media }}
    </head>
  5. Configure django-tinymce in your Django project

    master

    To use django-tinymce, you must perform three configuration steps:

    1. Add 'tinymce' to your INSTALLED_APPS in settings.py.
    2. Include tinymce.urls in your project's urls.py.
    3. Use HTMLField from tinymce.models in your Django models to render the TinyMCE editor.
    # settings.py
    INSTALLED_APPS = (
        ...
        'tinymce',
    )
    
    # urls.py
    from django.urls import path, include
    
    urlpatterns = [
        ...
        path('tinymce/', include('tinymce.urls')),
    ]
    
    # models.py
    from django.db import models
    from tinymce.models import HTMLField
    
    class MyModel(models.Model):
        ...
        content = HTMLField()
  6. Use the TinyMCE widget in Django forms

    master

    The recommended way to enable TinyMCE is by using the TinyMCE widget in your form field definitions. This allows you to specify custom attributes for the editor instance.

    To use it, import TinyMCE from tinymce.widgets and assign it to the widgets dictionary in a ModelForm's Meta class.

    from django import forms
    from django.contrib.flatpages.models import FlatPage
    from tinymce.widgets import TinyMCE
    
    class FlatPageForm(forms.ModelForm):
    
        class Meta:
            model = FlatPage
            widgets = {'content': TinyMCE(attrs={'cols': 80, 'rows': 30})}
  7. Verify django-tinymce installation

    master

    To verify that django-tinymce is installed and configured correctly, you can run a manual test in an isolated environment:

    1. Create and activate a virtual environment:
      virtualenv --no-site-packages env
      . env/bin/activate
    2. Install dependencies:
      pip install Django django-tinymce
    3. Set the DJANGO_SETTINGS_MODULE environment variable (e.g., export DJANGO_SETTINGS_MODULE='tests.settings').
    4. Create a test project and migrate:
      django-admin startproject tinymce_test
      cd tinymce_test
      python manage.py migrate
    5. Create a superuser and run the server:
      python manage.py createsuperuser
      python manage.py runserver
    6. Navigate to an admin page containing a TinyMCE widget (e.g., http://localhost:8000/admin/testapp/testpage/add/). If you see the TinyMCE editor instead of a standard textarea, the installation is successful.
    virtualenv --no-site-packages env
    . env/bin/activate
    pip install Django django-tinymce
    export DJANGO_SETTINGS_MODULE='tests.settings'
    django-admin startproject tinymce_test
    cd tinymce_test
    python manage.py migrate
    python manage.py createsuperuser
    python manage.py runserver
    # Check http://localhost:8000/admin/testapp/testpage/add/
  8. Install django-tinymce

    master

    To install django-tinymce in your Django project, follow these steps:

    1. Install the package via pip:
    pip install django-tinymce
    1. Add 'tinymce' to your INSTALLED_APPS in settings.py.

    2. Include the TinyMCE URLs in your project's urls.py:

    urlpatterns = patterns('',
        ...
        path('tinymce/', include('tinymce.urls')),
        ...
    )
    pip install django-tinymce
    
    INSTALLED_APPS = (
        ...
        'tinymce',
        ...
    )
    
    urlpatterns = patterns('',
        ...
        path('tinymce/', include('tinymce.urls')),
        ...
    )
  9. Configure django-tinymce settings

    master

    You can customize the behavior of django-tinymce by adding the following settings to your settings.py file:

    • TINYMCE_JS_URL: The URL of the TinyMCE javascript file. Defaults to settings.STATIC_URL + 'tinymce/tinymce.min.js'.
    • TINYMCE_DEFAULT_CONFIG: A dictionary containing the default TinyMCE configuration. If not set, it uses a default set of plugins, toolbar, and theme. Note: Only use the language attribute here if you want to force a language different from Django's current active language.
    • TINYMCE_COMPRESSOR: A boolean indicating whether to use the TinyMCE compressor (gzips JS files into a single stream). Defaults to False. Setting this to True can significantly reduce download size and initialization time.
    • TINYMCE_EXTRA_MEDIA: A dictionary of extra media (like CSS or JS) to include on the page with the widget. Defaults to None.
    • TINYMCE_FILEBROWSER: A boolean indicating whether to use django-filebrowser as a custom filebrowser. Defaults to True if 'filebrowser' is in INSTALLED_APPS, otherwise False.
    TINYMCE_JS_URL = 'http://debug.example.org/tiny_mce/tiny_mce_src.js'
    TINYMCE_DEFAULT_CONFIG = {
        "height": "320px",
        "width": "960px",
        "menubar": "file edit view insert format tools table help",
        "plugins": "advlist autolink lists link image charmap preview anchor searchreplace visualblocks code "
        "codesample emoticons fullscreen insertdatetime media table code help wordcount save directionality",
        "toolbar": "undo redo | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft "
        "aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor "
        "backcolor removeformat | pagebreak | charmap emoticons | "
        "fullscreen  preview save print | image media link anchor codesample | ltr rtl | code",
        "custom_undo_redo_levels": 10,
        "language": "es",  # To force a specific language instead of the Django current language.
        "browser_spellcheck": True,
    }
    TINYMCE_COMPRESSOR = True
    TINYMCE_EXTRA_MEDIA = {
        'css': {
            'all': [
                ...
            ],
        },
        'js': [
            ...
        ],
    }
  10. Configure TinyMCE via mce_attrs

    master

    The TinyMCE widget accepts an mce_attrs keyword argument (default: {}) to pass extra configuration options to the TinyMCE editor.

    • Options from settings.TINYMCE_DEFAULT_CONFIG are applied first and can be overridden by mce_attrs.
    • Python types are automatically converted to JavaScript types using standard JSON encoding (e.g., 'nowrap': True becomes nowrap: true).

    Special Option:

    • content_language: Sets the language of the widget content. This affects the language and directionality configuration options. It defaults to the current Django language code. To change the interface language specifically, use the language option within mce_attrs.
  11. Migration: Update legacy link and image list options

    master

    Recent versions of TinyMCE no longer support external_link_list_url and external_image_list_url. Additionally, the helper views tinymce.views.render_to_link_list and tinymce.views.render_to_image_list are no longer supported.

    Action Required: Replace these legacy options with link_list and image_list respectively, and ensure they point to a view returning the required JSON format (as described in the 'Configure external link and image lists' guide).