Skip to main content

A Django model field and widget that renders a customizable WYSIWYG/rich text editor

Project description

Latest Version https://travis-ci.org/jaap3/django-richtextfield.svg?branch=master https://coveralls.io/repos/jaap3/django-richtextfield/badge.svg?branch=master

A Django model field and widget that renders a customizable rich text/WYSIWYG widget.

Supports global editor settings, reusable editor profiles and per field & widget settings. There’s built-in support for pluggable server side content sanitizers.

Tested with TinyMCE and CKEditor. Designed to be easily extended to use other editors.

Quickstart

Install django-richtextfield and add it to your Django project’s INSTALLED_APPS, django.contrib.admin must also be in INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    ...
    'djrichtextfield'
]

Add the urls to the project’s urlpatterns:

path('djrichtextfield/', include('djrichtextfield.urls'))

Configure django-richtextfield in settings.py:

DJRICHTEXTFIELD_CONFIG = {
    'js': ['//tinymce.cachefly.net/4.1/tinymce.min.js'],
    'init_template': 'djrichtextfield/init/tinymce.js',
    'settings': {
        'menubar': False,
        'plugins': 'link image',
        'toolbar': 'bold italic | link image | removeformat',
        'width': 700
    }
}

Now you’re ready to use the field in your models:

from djrichtextfield.models import RichTextField

class Post(models.Model):
    content = RichTextField()

or forms:

from djrichtextfield.widgets import RichTextWidget

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=RichTextWidget())

Configuration

Define the DJRICHTEXTFIELD_CONFIG dictionary in your project settings. This dictionary can have the following keys:

Javascript souce(s)

'js'

A list of required javascript files. These can be URLs to a CDN or paths relative to your STATIC_URL e.g.:

'js': ['//cdn.ckeditor.com/4.4.4/standard/ckeditor.js']

or:

'js': ['path/to/editor.js', 'path/to/plugin.js']

CSS souce(s)

'css'

A dictionary of CSS files required for various forms of output media. These can be URLs to a CDN or paths relative to your STATIC_URL e.g.:

'css': {
    'all': [
        'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css'
    ]
}

or:

'css': {'all': ['path/to/editor.css', 'path/to/plugin.css']}

Editor init template

'init_template'

Path to the init template for your editor. Currently django-richtextfield ships with two templates, either:

'init_template': 'djrichtextfield/init/tinymce.js'

or:

'init_template': 'djrichtextfield/init/ckeditor.js'

Editor settings

'settings'

A Python dictionary with the default configuration data for your editor e.g.:

'settings': {  # TinyMCE
    'menubar': False,
    'plugins': 'link image',
    'toolbar': 'bold italic | link image | removeformat',
    'width': 700
}

or:

'settings': {  # CKEditor
    'toolbar': [
        {'items': ['Format', '-', 'Bold', 'Italic', '-',
                   'RemoveFormat']},
        {'items': ['Link', 'Unlink', 'Image', 'Table']},
        {'items': ['Source']}
    ],
    'format_tags': 'p;h1;h2;h3',
    'width': 700
}

Editor profiles

'profiles'

This is an optional configuration key. Profiles are “named” custom settings used to configure specific type of fields. You can configure profiles like this:

'profiles': {
    'basic': {
        'toolbar': 'bold italic | removeformat'
    },
    'advanced': {
        'plugins': 'link image table code',
        'toolbar': 'formatselect | bold italic | removeformat |'
                   ' link unlink image table | code'
    }
}

Content sanitizers

'sanitizer'

This is an optional configuration key. A sanitizer can be used to process submitted values before it is returned by the widget. By default no processing is performed on submitted values. You can configure a sanitizer either by providing a function or an importable path to a function, like so:

'sanitizer': lambda value: '<h1>Title</h1>' + value

or:

'sanitizer': 'bleach.clean'
'sanitizer_profiles'

This is an optional configuration key. It is possible to override the default or configured sanitizer for each of the configured profiles. For example to set a custom sanitizer for the advanced profile:

'sanitizer_profiles': {
    'advanced': lambda value: value + 'This text has been sanitized.'
}

Field & Widget settings

You can override the default settings per field:

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=RichTextWidget())
    content.widget.field_settings = {'your': 'custom', 'settings': True}

or:

class Post(models.Model):
    content = RichTextField(
        field_settings={'your': 'custom', 'settings': True},
        sanitizer='bleach.linkify'
    )

It’s recommended to use profiles, they make it easier to switch configs or even editors on a later date. You use a profile like this:

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=RichTextWidget(field_settings='basic'))

or:

class Post(models.Model):
    content = RichTextField(field_settings='advanced')

Custom init / Using another editor

It should be fairly easy to use this project with another editor. All that’s required is to configure DJRICHTEXTFIELD_CONFIG to load the right Javascript/CSS files and to create a custom init template.

For example, to use jQuery based Summernote (lite) editor:

DJRICHTEXTFIELD_CONFIG = {
    'js': [
        '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js',
        '//cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.js',
    ],
    'css': {
        'all': [
            '//cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.css',
        ]
    },
    'init_template': 'path/to/init/summernote.js',
    'settings': {
        'followingToolbar': False,
        'minHeight': 250,
        'width': 700,
        'toolbar': [
            ['style', ['bold', 'italic', 'clear']],
        ],
    }
}

Init template

The init template is a Django template (so it should be in the template and not in the static directory). It contains a tiny bit of Javascript that’s called to initialize each editor. For example, the init template for Summernote would like this:

$('#' + id).summernote(settings)

The init template has the following Javascript variables available from the outer scope:

$e

jQuery wrapped textarea to be replaced (using the jQuery version bundled with Django’s admin)

id

The id attribute of the textarea

default_settings

DJRICHTEXTFIELD_CONFIG['settings'] as a JS object

custom_settings

The field_settings as a JS object

settings

Merge of default_settings and custom_settings

Handling uploads & other advanced features

django-richtextfield built to be editor agnostic. This means that it’s up to you to handle file uploads, show content previews and support other “advanced” features.

History

1.4.0 (2019-01-31)

  • Add support for pluggable server side content sanitizers

1.3.0 (2018-11-05)

  • Allow CSS files to be included by a RichTextWidget

1.2.4 (2018-09-25)

  • Fix display issue in Django 2.1’s admin interface

1.2.3 (2018-09-11)

  • Add support for Django 2.1

1.2.2 (2018-06-12)

  • Conditionally load the (un)minified version of jquery depending on DEBUG

  • Load jQuery before all other scripts

1.2.1 (2018-01-18)

  • Add ['admin/js/vendor/jquery/jquery.min.js', 'admin/js/jquery.init.js'] to RichTextWidget.media.js. This makes the widget usable outside of the admin (but still requires django.contrib.admin to be in INSTALLED_APPS) and prevents javascript errors inside the admin in certain edge cases.

1.2 (2017-12-04)

  • Remove support for Django < 1.11

  • Add support for Django 2.0

1.1 (2016-01-14)

  • Remove support for Django < 1.8

  • Tested with Django 1.8 & Django 1.9

1.0.1 (2014-11-13)

  • Fix unicode error

1.0 (2014-09-30)

  • First release

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-richtextfield-1.4.0.tar.gz (17.8 kB view details)

Uploaded Source

File details

Details for the file django-richtextfield-1.4.0.tar.gz.

File metadata

  • Download URL: django-richtextfield-1.4.0.tar.gz
  • Upload date:
  • Size: 17.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.30.0 CPython/3.6.6

File hashes

Hashes for django-richtextfield-1.4.0.tar.gz
Algorithm Hash digest
SHA256 26d98cac9b113df749ec00827f242e9c3844a1b4fb37554763d58371cc7d5217
MD5 cfd2192428bb2ef732da8b21ada447e3
BLAKE2b-256 fbc5aae0a4042e65c7b4c88a2feb7a16643575bae6724444fe9a9264516949d7

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page