Git Product home page Git Product logo

django-ckeditor-5's Introduction

Django CKEditor 5

CKEditor 5 for Django >= 2.0

Quick start

pip install django-ckeditor-5
  1. Add "django_ckeditor_5" to your INSTALLED_APPS in your project/settings.py like this:
INSTALLED_APPS = [
    ...
    'django_ckeditor_5',
]
  1. Also, in your project/settings.py add:
  STATIC_URL = '/static/'
  MEDIA_URL = '/media/'
  MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

  customColorPalette = [
        {
            'color': 'hsl(4, 90%, 58%)',
            'label': 'Red'
        },
        {
            'color': 'hsl(340, 82%, 52%)',
            'label': 'Pink'
        },
        {
            'color': 'hsl(291, 64%, 42%)',
            'label': 'Purple'
        },
        {
            'color': 'hsl(262, 52%, 47%)',
            'label': 'Deep Purple'
        },
        {
            'color': 'hsl(231, 48%, 48%)',
            'label': 'Indigo'
        },
        {
            'color': 'hsl(207, 90%, 54%)',
            'label': 'Blue'
        },
    ]

  CKEDITOR_5_CUSTOM_CSS = 'path_to.css' # optional
  CKEDITOR_5_FILE_STORAGE = "path_to_storage.CustomStorage" # optional
  CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                    'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],

    },
    'extends': {
        'blockToolbar': [
            'paragraph', 'heading1', 'heading2', 'heading3',
            '|',
            'bulletedList', 'numberedList',
            '|',
            'blockQuote',
        ],
        'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough',
        'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage',
                    'bulletedList', 'numberedList', 'todoList', '|',  'blockQuote', 'imageUpload', '|',
                    'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat',
                    'insertTable',],
        'image': {
            'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft',
                        'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side',  '|'],
            'styles': [
                'full',
                'side',
                'alignLeft',
                'alignRight',
                'alignCenter',
            ]

        },
        'table': {
            'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells',
            'tableProperties', 'tableCellProperties' ],
            'tableProperties': {
                'borderColors': customColorPalette,
                'backgroundColors': customColorPalette
            },
            'tableCellProperties': {
                'borderColors': customColorPalette,
                'backgroundColors': customColorPalette
            }
        },
        'heading' : {
            'options': [
                { 'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph' },
                { 'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1' },
                { 'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2' },
                { 'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3' }
            ]
        }
    },
    'list': {
        'properties': {
            'styles': 'true',
            'startIndex': 'true',
            'reversed': 'true',
        }
    }
}
  1. Include the app URLconf in your project/urls.py like this:
from django.conf import settings
from django.conf.urls.static import static

# [ ... ]

urlpatterns += [
    path("ckeditor5/", include('django_ckeditor_5.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Alternatively, you can use your own logic for file uploads. To do this, add the following to your settings.py file:

# Define a constant in settings.py to specify the custom upload file view
CK_EDITOR_5_UPLOAD_FILE_VIEW_NAME = "custom_upload_file"

Then, in your urls.py, include the custom upload URL pattern:

path("upload/", custom_upload_function, name="custom_upload_file"),

This allows users to customize the upload file logic by specifying their own view function and URL pattern.

  1. Add to your project/models.py:
from django.db import models
from django_ckeditor_5.fields import CKEditor5Field


class Article(models.Model):
    title=models.CharField('Title', max_length=200)
    text=CKEditor5Field('Text', config_name='extends')

Includes the following ckeditor5 plugins:

Essentials, UploadAdapter, CodeBlock, Autoformat, Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, BlockQuote, Heading, Image, ImageCaption, ImageStyle, ImageToolbar, ImageResize, Link, List, Paragraph, Alignment, Font, PasteFromOffice, SimpleUploadAdapter, MediaEmbed, RemoveFormat, Table, TableToolbar, TableCaption, TableProperties, TableCellProperties, Indent, IndentBlock, Highlight, TodoList, ListProperties, SourceEditing, GeneralHtmlSupport, ImageInsert, WordCount, Mention, Style, HorizontalLine, LinkImage, HtmlEmbed, FullPage, SpecialCharacters, ShowBlocks, SelectAll, FindAndReplace

Examples

Example of using a widget in a form:

from django import forms

from django_ckeditor_5.widgets import CKEditor5Widget
from .models import Comment


class CommentForm(forms.ModelForm):
      """Form for comments to the article."""

      def __init__(self, *args, **kwargs):
          super().__init__(*args, **kwargs)
          self.fields["text"].required = False

      class Meta:
          model = Comment
          fields = ("author", "text")
          widgets = {
              "text": CKEditor5Widget(
                  attrs={"class": "django_ckeditor_5"}, config_name="comment"
              )
          }

Example of using a widget in a template:

{% extends 'base.html' %}
{% block header %}
    {{ form.media }} # Required for styling/js to make ckeditor5 work
{% endblock %}
{% block content %}
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit article">
    </form>
{% endblock %}

Custom storage example:

import os
from urllib.parse import urljoin

from django.conf import settings
from django.core.files.storage import FileSystemStorage


class CustomStorage(FileSystemStorage):
    """Custom storage for django_ckeditor_5 images."""

    location = os.path.join(settings.MEDIA_ROOT, "django_ckeditor_5")
    base_url = urljoin(settings.MEDIA_URL, "django_ckeditor_5/")

Changing the language:

You can change the language via the language key in the config

CKEDITOR_5_CONFIGS = {
  'default': {
      'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                  'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],
      'language': 'de',
  },

language can be either:

  1. a string containing a single language
  2. a list of languages
  3. a dict {"ui": <a string (1) or a list of languages (2)>}

If you want the language to change with the user language in django you can add CKEDITOR_5_USER_LANGUAGE=True to your django settings. Additionally you will have to list all available languages in the ckeditor config as shown above.

Creating a CKEditor5 instance from javascript:

To create a ckeditor5 instance dynamically from javascript you can use the ClassicEditor class exposed through the window global variable.

const config = {};
window.ClassicEditor
   .create( document.querySelector( '#editor' ), config )
   .catch( error => {
       console.error( error );
   } );
}

Alternatively, you can create a form with the following structure:

<form method="POST">
    <div class="ck-editor-container">
        <textarea id="id_text" name="text" class="django_ckeditor_5" >
        </textarea>
        <div></div> <!-- this div or any empty element is required -->
        <span class="word-count" id="id_text_script-word-count"></span>
   </div>
   <input type="hidden" id="id_text_script-ck-editor-5-upload-url" data-upload-url="/ckeditor5/image_upload/" data-csrf_cookie_name="new_csrf_cookie_name">
   <span id="id_text_script-span"><script id="id_text_script" type="application/json">{your ckeditor config}</script></span>
</form>

The ckeditor will be automatically created once the form has been added to the DOM.

To access a ckeditor instance you can either get them through window.editors

const editor = windows.editors["<id of your field>"];

or by registering a callback

//register callback
window.ckeditorRegisterCallback("<id of your field>", function(editor) {
  // do something with editor
});
// unregister callback
window.ckeditorUnregisterCallback("<id of your field>");

Allow file uploading as link:

By default only images can be uploaded and embedded in the content. To allow uploading and embedding files as downloadable links you can add the following to your config:

CKEDITOR_5_ALLOW_ALL_FILE_TYPES = True
CKEDITOR_5_UPLOAD_FILE_TYPES = ['jpeg', 'pdf', 'png'] # optional
CKEDITOR_5_CONFIGS = {
  'default': {
      'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                  'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', 'fileUpload' ], # include fileUpload here
      'language': 'de',
  },

Warning: Uploaded files are not validated and users could upload malicious content (e.g. a pdf which actually is an executable). Furthermore allowing file uploads disables any validation for the image upload as the backend can't distinguish between image and file upload. Exposing the file upload to all/untrusted users poses a risk!

Installing from GitHub:

cd your_root_project
git clone https://github.com/hvlads/django-ckeditor-5.git
cd django-ckeditor-5
yarn install
yarn run prod
cd your_root_project
python manage.py collectstatic

Example Sharing content styles between front-end and back-end:

To apply ckeditor5 styling outside of the editor, download content.styles.css from the official ckeditor5 docs and include it as a styleshet within your HTML template. You will need to add the ck-content class to the container of your content for the styles to be applied. https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/content-styles.html#sharing-content-styles-between-frontend-and-backend

<link rel="stylesheet" href="path/to/assets/content-styles.css" type="text/css">
...
<div class="ck-content">
<p>ckeditor content</p>
</div>

django-ckeditor-5's People

Contributors

ageu-meireles avatar cclauss avatar dependabot[bot] avatar goapunk avatar hvlads avatar jgwillard avatar jsolly avatar nattyg93 avatar wizardre avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-ckeditor-5's Issues

Forbidden (CSRF token missing or incorrect.): /ckeditor5/image_upload/

Hello again!

Thanks for helping me with the previous issue! Now the package seems to work, but not quite correctly. I'm having two different issues with different CBV views.

  1. In my ArticleUpdateView it woks fine unless I'm trying to upload an image. Then I got following error:

Forbidden (CSRF token missing or incorrect.): /ckeditor5/image_upload/
WARNING 2020-12-01 12:21:16,314 log 43989 140116421977856 Forbidden (CSRF token missing or incorrect.): /ckeditor5/image_upload/
[01/Dec/2020 12:21:16] "POST /ckeditor5/image_upload/ HTTP/1.1" 403 14187

  1. In my ArticleCreateView this error is also present. But, additionally, my Submit button doesn't work at all. It looks normally, but when it's pressed, nothing happens. If I change field type of my 'text' field to models.TextField, everything works fine.

As I understand, the first error is related to CSRF tokens, and the second error may be (possibly) related to form validity. But I don't know how to solve them. Please give me some ideas.

Problem with loading CKEditor5

document.querySelector(`[for$="${allEditors[i].id}"]`).style.float = 'none';

I'm trying to setup this app on one of my websites. However, when I attempt to load the page containing the CKEditor5 field, I get an error in my browser developer console that's related to the line above.

The exact error is:

Uncaught TypeError: Cannot read property 'style' of null
    at HTMLDocument.<anonymous> (app.js:25)

It seems that, for some reason, document.querySelector is returning no matches. I don't understand the syntax in this particular selector, so I'm unable to debug this. Any pointers?

'Could not upload file' issue

I couldn't find any information about how to handle the problem with the upload of a file, especially an image. Is there any solution?

I am unable to get the source editing to show up in the toolbar

Source editing plugin is not showing up in the toolbar despite being added to the config.

I am running the latest version (django-ckeditor-5==0.1.8).

My config looks as follows:

CKEDITOR_5_CONFIGS = {
'default': {
    'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],
},
'extends': {
    "htmlSupport": {
            "allow": [
                {"name": "/.*/", "attributes": True, "classes": True, "styles": True}
            ]
        },
    "mediaEmbed": {"previewsInData": "false", },
    'blockToolbar': [
        'paragraph', 'heading1', 'heading2', 'heading3',
        '|',
        'bulletedList', 'numberedList',
        '|',
        'blockQuote', 'imageUpload'
    ],
    'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough',
    'code','subscript', 'superscript', 'highlight', '|', 'codeBlock',
                'bulletedList', 'numberedList', 'todoList', '|',  'blockQuote', 'imageUpload', 'sourceEditing', '|',
                'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat',
                'insertTable'],
    'image': {
        'toolbar': ['toggleImageCaption', '|', 'imageTextAlternative', '|', 'imageStyle:alignLeft',
                    'imageStyle:alignRight', 'imageStyle:alignCenter', '|', 'imageStyle:side', 'imageStyle:inline',  '|'],
        'styles': [
            'full',
            'side',
            'alignLeft',
            'alignRight',
            'alignCenter',
        ]

    },
    'table': {
        'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells',
        'tableProperties', 'tableCellProperties' ],
        'tableProperties': {
            'borderColors': customColorPalette,
            'backgroundColors': customColorPalette
        },
        'tableCellProperties': {
            'borderColors': customColorPalette,
            'backgroundColors': customColorPalette
        }
    },
    'heading' : {
        'options': [
            { 'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph' },
            { 'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1' },
            { 'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2' },
            { 'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3' }
        ]
    },
    
},
'list': {
    'properties': {
        'styles': 'true',
        'startIndex': 'true',
        'reversed': 'true',
    }
},
}

Upload files such as PDFs

Is there an easy way that will allow me to upload files such as PDFs. Looks like the code only accepts images what would I have to remove in order to be able to upload PDFs.
@hvlads

new plugins

I need to install new plugin (Markdown)
How do i do it?

Add support of i18n url patterns

I had error because your package does not support locale prefix in urls, i fixed it this way:

urlpatterns = [
    path('ckeditor5/', include('django_ckeditor_5.urls')),
]

urlpatterns += i18n_patterns(
     // all my other urls
)

how it should works:

urlpatterns += i18n_patterns(
        path('ckeditor5/', include('django_ckeditor_5.urls')),
)

can you add i18n support, for example package nested admin, works perfectly when wrapped in i18n_patterns?

P.S. Awesome package!

[Accessibility] - Enable caption for HTML tables

Context

Table captions are recommended for sighted and unsighted users. This allows them to quickly understand what the table is about without having to start reading/listening through the data of the table.
See -> https://www.w3.org/WAI/tutorials/tables/caption-summary/

Ideal behavior

Captions can be turned on/off. This is how it works in the CKEditor5 demo editor.
image

Implementation Notes

According to the CKEDitor5 docs, this can be 'turned on' by adding the tableCaption plugin.

Drop-downs Bug

image

Drop-downs no longer work after adding the HorizontalLine Module.

File not found in static files - deployment fails

Hi

I tried out django-ckeditor-5 for the first time today. In development mode it worked very well.

However, I tried to deploy on Heroku and got following error message:

The CSS file 'django_ckeditor_5/src/custom_plugins/theme/titleform.css' references a file which could not be found:
django_ckeditor_5/src/custom_plugins/theme/@ckeditor/ckeditor5-ui/theme/mixins/_rwd.css

and in titleform.css I found follwing import, which can not be resolved.

@import "@ckeditor/ckeditor5-ui/theme/mixins/_rwd.css";

My environment:
asgiref==3.3.4
certifi==2020.12.5
dj-database-url==0.5.0
Django==3.2
django-ckeditor-5==0.0.14
django-crispy-forms==1.11.0
django-on-heroku==1.1.2
gunicorn==20.1.0
Pillow==8.2.0
psycopg2-binary==2.8.6
pytz==2021.1
sqlparse==0.4.1
whitenoise==5.2.0

Any idea how I can solve this? Let me know if you need more information.

Thanks and best regards,

Cedric

Ckeditor does not look good in Django admin dark theme

Context

In Django 3.2 and higher, the admin page respects the theme of the system. In MacOS, if the theme is dark, the whole django admin UI is dark as well.

What seems to be happening is that the text color is being changed to white, but the background of ckeditor stays white as well.

Current Behavior

1 - Turn on Dark mode at the OS or browser level
2 - Visit the admin page and open a page with ckeditor
image
Text is white on white

Ideal behavior

Ckeditor is either not affected by theme change or it switches into its own dark mode.

Workarounds

1 - If you highlight all the text and make it black, it makes it readable, but code blocks stay white
image

2 - You could use the django-non-dark-admin module to disable admin dark mode (This is what I did)

3 - You could disable dark theme by modifying the django admin css as explained in this stackoverflow thread.

4 - Only use CKeditor outside of the admin page

5 - Use CKEDITOR_5_CUSTOM_CSS variable in settings.py to point to alternate CSS?

Other Resources

CKeditor 5 Theme customization page

Final thoughts

I've disabled the dark Django admin page for now, but any workarounds would be much appreciated!!!

Environment

django-ckeditor-5==0.1.3
Python==3.9.7

MathType and ChemType

Whoa! Thank you so much for this fantastic work! I have a problem, I can't install MathType (CKEDITOR's plugin), I tried to add it under 'toolbar', but nothing...I think it's just missing the plugin. How can I fix this?

Mention how to add ckeditor5 styles to the front end of your app

Context

In order to get ckeditor5 CSS styles into the front end (like a post detail route), you need to download the CSS file from the CKeditor5 docs.

Then you include it on your page

<link rel="stylesheet" href="path/to/assets/content-styles.css" type="text/css">

Finally, you want to make sure that the ck-content class is included in the parent element that contains your ckeditor5 content. For me, it was something like this:

<div class="ck-content">
    <p>{{ post.content|safe }}</p>
</div>

I don't think this is obvious and should be included in an example or in the readme.

YouTube video does not work

In the admin panel, when editing a post, the video is shown. But when viewing a post on the frontend, the video is not displayed.

In this case, the html code is there.

Image media is not uploading on AWS S3

When I was uploaded image from backend django admin then the image is not getting upload on aws s3 media folder with name django-ckeditor-5/example.img. It is creating one folder with name django-ckeditor-5 on local server. but Not uploading on aws s3 media folder.
I have putted both path but not working
path(r'^ckeditor5/(?P<path>.*)/?$', include('django_ckeditor_5.urls')),
path("ckeditor5/", include('django_ckeditor_5.urls')),
and tried with this one also
re_path(r'^(?:.*)/?$', include('frontend.urls'))

mine issue is exact same as issue #10
Am I applying it in wrong way?

Click here to check my question on stackoverflow.

change language of ckeditor

hey there i have 2 questions:

1)how to change language of ckeditor?

2)how to change type, version of ckeditor?

Thanks!

Bad Parse to database

i have problem with v 0.0.13 , try to make bold text but i got this in database or view, it doesnt save a html tag i was try some tools.
Screenshot from 2021-04-22 16-09-25

Can't embed a YouTube video

I'm trying to insert a YouTube video link via the "Insert media" button in the editor. While the video preview showing up in the editor, it doesn't appear on the rendered page. Instead, it generates HTML like this:
<figure class="media"><oembed url="https://www.youtube.com/watch?v=XXXXXXXX"></oembed></figure>
According to the description, the MediaEmbed plugin is included in this package and it should work with YouTube links. Isn't it?
Thanks!

Upload media Issue

When I was uploaded image from backend django admin then the image is not getting upload on aws s3 media folder with name django-ckeditor-5/example.img. It is creating one folder with name django-ckeditor-5 on local server. but Not uploading on aws s3 media folder.

403 error while uploading image on admin interface

Hello, I've just now upgraded to django-ckeditor 5 and when trying to upload an image, I get a 403 error saying csrf token missing

[29/Aug/2022 11:40:57] "GET /admin/jsi18n/ HTTP/1.1" 200 3343 Forbidden (CSRF token missing.): /ckeditor5/image_upload/ [29/Aug/2022 11:43:07] "POST /ckeditor5/image_upload/ HTTP/1.1" 403 2506

it's my first time submitting a github issue so if this has nothing to do with django-ckeditor-5 then I'll appriciate if I'm pointed to the right resource.

Set link into image.

Hi, my apologies, certainly this question is not an issue. I'm trying set a link into image and when I select the image, the link icon is disabled and doesn't work:

Captura de pantalla de 2022-09-20 15-45-36

Would be possible a behaviour like this?
Captura de pantalla de 2022-09-20 15-45-10

I'm using django-ckeditor-5 version 0.1.8
Do I need any extra configuration?

Best regards,
Jorge.

Remove unsafe-inline styles to respect a content security policy?

Context

I have a CSP (Content Security Policy) for my app. When I turn off 'unsafe-inline' for styles, I see a lot of errors in the console
image

Steps to reproduce

1 - Install django-csp
2 - Add the following security policy in settings.py

CSP_STYLE_SRC = "'self'"

3 - Start using CKEditor in edit mode
Lots of errors in console. Most functionality is maintained, but some things are broken (like image re-size).

Further Thoughts

According to the CKEditor docs:

Note: You can extract styles to a separate .css file during the editor building process and remove this directive.

  • Certain editor content styles to work properly. For instance, you are going to need it if you want to enable such editor features as font or text alignment or any other feature that uses inline style="..." attributes in the content.

I wonder if this is something we can do ourselves or if it requires work for the maintainers. I do see code in config.webpack.js that looks like it performs the CSS extraction.

Ckeditor5 fails when using a widget on a field with django.forms.TextArea

I was previously using django-ckeditor which is built on ckeditor4 and am trying to migrate to ckeditor5 with this module.

It works perfectly on the admin page
image

But ckeditor5 does not load in my post-create route when there is a wiget attached to the form field. My goal in using the widget is to add a class to the field so that line numbers show up when using Prisim.js.

forms.py

from django import forms
from .models import Post
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            "content",
        )

        widgets = {
            "content": forms.Textarea(attrs={"class": "line-numbers"}),
        }

Workaround

If I remove the widget, ckeditor loads successfully.

from django import forms
from .models import Post
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            "content",
        )

Environment

Python==3.9.7
django-ckeditor-5==0.1.0
django==3.2.13

Discussion

I think this might be because this module was created to be used on the admin page as mentioned in this issue.

Google Cloud Bucket upload fails

I am using django-storages with storages.backends.gcloud.GoogleCloudStorage backend. I have set these settings:
CKEDITOR5_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' CKEDITOR_5_UPLOADS_FOLDER = 'uploads/'

However, when I try to upload an image, I get this error:

Internal Server Error: /ckeditor5/image_upload/
Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 54, in upload_file
    url = handle_uploaded_file(request.FILES["upload"])
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 41, in handle_uploaded_file
    fs = storage(location=uploads_path)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/backends/gcloud.py", line 97, in __init__
    check_location(self)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/utils.py", line 93, in check_location
    if storage.location.startswith('/'):
AttributeError: 'PosixPath' object has no attribute 'startswith'
[04/May/2022 15:00:20] "POST /ckeditor5/image_upload/ HTTP/1.1" 500 105904

Other relevant settings:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 
MEDIA_URL = '/media/'

django-ckeditor4 worked fine, so is it a question of supporting GCB storage or am I missing something in my settings?

Changing the default HTML for uploaded images

Hi,

Would it be possible to replace the default HTML code that displays the images? I need to implement a bootstrap modal for images to open them full screen. Currently, the saved images are displayed as:

<figure class="image image-style-align-center image_resized" style="width:100%;"><img src="URL_TO_IMAGE"></figure>

And I would like to add a bootstrap modal for each image. Or an alternative would be making the images clickable to open in a new tab. Thank you!

Text Aligment Not Save

i cant save text alignment, it not work anymore, after edit with django admin and open it again, it back to default state

Media embed feature produces output that does not contain previews of embedded media

Context

I want to show a Youtube video inside a blog post. It works great while editing, but as soon as I view the post on my website, I no longer see the media preview.

Video Shows on the admin page
image

Nothing shows in viewing mode. It appears that the elements are there, but they don't render
image

Steps to reproduce

1 - Copy a link to a Youtube video (such as https://www.youtube.com/watch?v=C5M2cy80LxE )
2 - Paste this link into the editing area or using the 'Media Embed' tool within ckeditor 5
3 - Video preview shows as expected in the editor
4 - View the content outside the editor (like a user would)
No preview is shown

Research

I found this SO thread that suggests adding "previewsInData": "true" to the config, but this didn't work for me.

mediaEmbed: {
    previewsInData:true
},

According to the Ckeditor 5 docs

By default, the media embed feature produces output that does not contain previews of embedded media, called the semantic output. This means that you need to transform the output elements into real media on your target website.

There are many ways to do that. The simplest, plug-and-play solutions are described here. You can also implement this transformation as part of your back-end service or you can use different services than described in this section.

The docs then go into various ways to accomplish this, one being adding Iframely.

Ideal behavior

Media embeds (such as Youtube videos) render in viewing mode.

support ImageInsert plugin

Context

Currently, we have the ability to upload images using the imageUpload toolbar item. Unfortunately, this does not work when using images that are hosted elsewhere and you do not want to upload a copy.

If you add imageUpload to the toolbar, you can upload images, but there is no way to reference the image via URL.
image

Workaround

You can add the image manually using a tag and enable the source toolbar item.
< image src="..." > example image < / img >

But this is a lot of extra typing.

Ideal behavior

According to the CKeditor5 documentation if we install the ImageInsert extension, we can replace imageUpload with insertImage. This toolbar item has an extra dropdown next to the image icon that lets you add an image via URL
image

Once this is added, we should be able to just replace imageUpload with insertImage in our toolbar configuration within settings.json

Issue with new plugin

Hi, i have issue installing new plugins
i follow the instruction from other closed post:
#21

Clone the repo
npm install
npm install @ckeditor/ckeditor5-word-count
https://ckeditor.com/docs/ckeditor5/latest/features/word-count.html#installation

inside app.js
import WordCount from '@ckeditor/ckeditor5-word-count/src/wordcount';
passing WordCount as plugin value

and
npm run prod

the result is:
Uncaught CKEditorError: ckeditor-duplicated-modules

i did the same inside ckeditor.js i imported
import WordCount from '@ckeditor/ckeditor5-word-count/src/wordcount';
and put WordCount in the ClassicEditor.builtinPlugins
Same result

What im doing wrong?
Thanks

Add General HTML Support

Context

It would be great if we had more control over what elements are allowed within CKeditor In the current version, I can't add an <iframe>. This seems like a natural progression since source editing was turned on recently.

According to the ckeditor docs:

The General HTML Support (“GHS”) feature allows developers to easily enable HTML features that are not explicitly supported by any other dedicated CKEditor 5 plugins. It acts similarly to Advanced Content Filter (ACF) from CKEditor 4, a feature that filters incoming HTML content by transforming and deleting disallowed elements, attributes, classes and styles. GHS allows for adding this kind of markup to the source and prevents it from being filtered from the editor window and the output.

Things to consider

There are security implications, but I think it makes sense to provide users a way to enable these elements and assume the risks themselves.

Check the correct settings.CKEDITOR_5_CONFIGS 'comment'

Greetings everyone

i was trying to implement django ckeditor 5. It works completly fine on django admin but when i implement on django templates it show me ----> Check the correct settings.CKEDITOR_5_CONFIGS 'comment' <---- error. can you please help me resolve this error.

Screen Shot 2022-09-17 at 3 21 38 PM

403 Forbidden (CSRF token missing or incorrect.) when attempting to upload an image

Context

Steps to Reproduce

1 - Add an image using the image option in the toolbar
2 - CSRF error
2022-05-27_16-45-03 (1)

Workaround

Following this SO answer I added the following to django_ckeditor_5.views

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def upload_file(request):
    if request.method == "POST" and request.user.is_staff:
        form = UploadFileForm(request.POST, request.FILES)
        try:
            image_verify(request.FILES["upload"])
        except NoImageException as ex:
            return JsonResponse({"error": {"message": "{}".format(str(ex))}})
        if form.is_valid():
            url = handle_uploaded_file(request.FILES["upload"])
            return JsonResponse({"url": url})
    raise Http404(_("Page not found."))

and the image uploads sucessfully.

This also appears to be the same thing django-ckeditor is doing. See line 136 in their view

upload = csrf_exempt(ImageUploadView.as_view())

Environment
Python==3.9.7
django-ckeditor-5==0.1.0
django==3.2.13

Compatibility with django-modeltranslation

Hello! My website uses django-modeltranslation to support different languages. When I try to install django-ckeditor-5, I got the following error:

django.core.exceptions.ImproperlyConfigured: CKEditor5Field is not supported by modeltranslation.

Here is some additional information from the sunserver command:

File "/media/mike/Data/Websites/raptors/raptors/news/translation.py", line 7, in
translator.register(Article, ArticleTranslationOptions)
File "/media/mike/Data/Websites/raptors-env/lib/python3.9/site-packages/modeltranslation/translator.py", line 457, in register
self._register_single_model(model, opts)
File "/media/mike/Data/Websites/raptors-env/lib/python3.9/site-packages/modeltranslation/translator.py", line 474, in _register_single_model
add_translation_fields(model, opts)
File "/media/mike/Data/Websites/raptors-env/lib/python3.9/site-packages/modeltranslation/translator.py", line 149, in add_translation_fields
translation_field = create_translation_field(
File "/media/mike/Data/Websites/raptors-env/lib/python3.9/site-packages/modeltranslation/fields.py", line 67, in create_translation_field
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: CKEditor5Field is not supported by modeltranslation.

Is it possible to use both django-ckeditor-5 and django-modeltranslation?

User ID in the upload path

Hi,
I would like to change the default upload path and add a user id to the path. I've found the CKEDITOR_5_UPLOADS_FOLDER setting, but is there any way to add a user id to the path, for example, /content/{USER_ID}/?
Thanks!

FastDevVariableDoesNotExist inside widget.html due to {{ errors }} tag

Context

I use a package called django-fastdev that surfaces FastDevVariableDoesNotExist whenever a template variable does not exist (instead of rendering an empty string).

This causes fatal errors in django-ckeditor-5

Steps to Reproduce

1 - Install django-fastdev
2 - Access Ckeditor 5 within your Django app

FastDevVariableDoesNotExist
errors does not exist in context.

Expected Behavior

Only show {{ errors }} if errors actually exist.

Environment

  • Version of API: 0.1.3

Plugins usage

Hi, sorry for opening an issue for that, but can you please tell how to set numbered list style types to have a menu to select from different types of styles, like numbers or roman?
Thanks in advance and sorry again for that.
Like that:
image

0.1.8 Can be used, 0.1.9 No module named 'django_ckeditor_5'

root@cdasia:/home# pip install django-ckeditor-5
Requirement already satisfied: django-ckeditor-5 in /usr/local/lib/python3.9/dist-packages (0.1.9)
Requirement already satisfied: Django==4.1 in /usr/local/lib/python3.9/dist-packages (from django-ckeditor-5) (4.1)
Requirement already satisfied: Pillow==9.0.1 in /usr/local/lib/python3.9/dist-packages (from django-ckeditor-5) (9.0.1)
Requirement already satisfied: asgiref<4,>=3.5.2 in /usr/local/lib/python3.9/dist-packages (from Django==4.1->django-ckeditor-5) (3.5.2)
Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.9/dist-packages (from Django==4.1->django-ckeditor-5) (0.4.2)

root@cdasia:/home# python3
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.

import django_ckeditor_5
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'django_ckeditor_5'

whitenoise.storage.MissingFileError .../ckeditor5-ui/theme/mixins/_rwd.css could not be found when running collectstatic

Context

I have recently been exploring using WhiteNoise in my Django app. I see an error whenever I run collectstatic.

Steps to Reproduce

1 - Install WhiteNoise
2 - manage.py collectstatic
Error in terminal

Post-processing 'django_ckeditor_5/src/custom_plugins/theme/titleform.css' failed!

Traceback (most recent call last):
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/manage.py", line 21, in <module>
    main()
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
    output = self.handle(*args, **options)
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle
    collected = self.collect()
  File "/Users/johnsolly/Documents/code/blogthedata/django_project/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect
    raise processed
whitenoise.storage.MissingFileError: The file 'django_ckeditor_5/src/custom_plugins/theme/@ckeditor/ckeditor5-ui/theme/mixins/_rwd.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x106ca5070>.

The CSS file 'django_ckeditor_5/src/custom_plugins/theme/titleform.css' references a file which could not be found:
  django_ckeditor_5/src/custom_plugins/theme/@ckeditor/ckeditor5-ui/theme/mixins/_rwd.css

Please check the URL references in this CSS file, particularly any
relative paths which might be pointing to the wrong location.

I checked the file and I think there is an issue on line 6 where it attempts to import a CSS file that does not exist.

/*  django_ckeditor_5/static/django_ckeditor_5/src/custom_plugins/theme/titleform.css */
 @import "@ckeditor/ckeditor5-ui/theme/mixins/_rwd.css";

Environment

  • Version of API: 0.1.3

Not uploading images

Opens dialog to select file from PC but fails to load it into the editor. Any fix ?
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.