Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enableReadOnlyMode & refactor upload_url to a class #195

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,56 @@ Custom storage example:
base_url = urljoin(settings.MEDIA_URL, "django_ckeditor_5/")


Rename the uploaded images using uuid:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can rename the images using uuid value and maintaning the extension in lower case. Example if your uploaded image original name was `my-image.JPG` now would be `acb34ded-f203-431a-9005-387cc24a892e.jpg`

You need to specity the settings variable with True value

.. code-block:: python

CKEDITOR_5_UPLOAD_IMAGES_RENAME_UUID = True


Custom upload_url example:
^^^^^^^^^^^^^^^^^^^^^^^
You can use a custom upload_url to satisfy your business logic needs.

If you want to use a custom upload_url, You need to create a custom view class that extends UploadImageView

.. code-block:: python

import os
import uuid
from django_ckeditor_5.views import UploadImageView


class CustomUploadImageView(UploadImageView):
"""Custom View to upload images for django_ckeditor_5 images."""
def handle_uploaded_file(self, f):
fs = self.get_storage_class()()
filename = f.name.lower()
# Here you can apply custom actions before the file is saved. For example optimize the image size
if getattr(settings, "CKEDITOR_5_UPLOAD_IMAGES_RENAME_UUID", None) is True:
new_file_name = f"{uuid.uuid4()}{os.path.splitext(filename)[1]}"
filename = fs.save(new_file_name, f)
# Here you can apply custom actions after the file is saved
return fs.url(filename)

You need to add the custom url to your app urls.py file

.. code-block:: python

from . import views # or from .views import CustomUploadImageView
path("custom_image_upload/", views.CustomUploadImageView.as_view(),name="ck_editor_5_upload_image",),

Finally You need to specify in the settings the CKEDITOR_5_UPLOAD_IMAGE_URL_NAME variable with the name of your custom_image_upload url view

.. code-block:: python

CKEDITOR_5_UPLOAD_IMAGE_URL_NAME = "your_app_name:ck_editor_5_upload_image"


Changing the language:
^^^^^^^^^^^^^^^^^^^^^^
You can change the language via the ``language`` key in the config
Expand Down
3 changes: 3 additions & 0 deletions django_ckeditor_5/static/django_ckeditor_5/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ function createEditors(element = document.body) {
wordCountWrapper.innerHTML = '';
wordCountWrapper.appendChild(wordCountPlugin.wordCountContainer);
}
if(editorEl.hasAttribute("disabled")){
editor.enableReadOnlyMode( 'docs-snippet' );
Copy link
Owner

@hvlads hvlads Apr 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your work on the code. Is it intended to use the same id for all editors?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hvlads sorry. I don't understand

Copy link
Owner

@hvlads hvlads Apr 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the lockId: string | symbol parameter:
This parameter serves as a unique identifier for setting the editor into a read-only state. It's essential to ensure that each lock Id is unique within your codebase.

editor.enableReadOnlyMode( 'my-feature-id' );
editor.enableReadOnlyMode( 'my-other-feature-id' );
// ...
editor.disableReadOnlyMode( 'my-feature-id' );
editor.isReadOnly; // true.
editor.disableReadOnlyMode( 'my-other-feature-id' );
editor.isReadOnly; // false.

Parameters
lockId : string | symbol
A unique ID for setting the editor to the read-only state.

In the loop, you're adding "docs-snippet" to all editors with the "disabled" attribute.

Shouldn't we do this?
const lockId = docs-snippet-${i};
editor.enableReadOnlyMode(lockId);

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Juanita, do you need any assistance with this? Also, I wanted to confirm if the class UploadImage View is still relevant now that files are being uploaded as well. Let me know if you need any clarification. Thanks!

}
editors.push(editor);
}).catch(error => {
console.error((error));
Expand Down
4 changes: 2 additions & 2 deletions django_ckeditor_5/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.urls import path

from . import views
from .views import UploadImageView

urlpatterns = [
path("image_upload/", views.upload_file, name="ck_editor_5_upload_file"),
path("image_upload/", UploadImageView.as_view(), name="ck_editor_5_upload_image"),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a potentially breaking change if anyone uses reverse("ck_editor_5_upload_file") (I do :) ). Is this renaming from file to image really necessary? If it is it should be marked as a breaking change somehow, there currently is no changelog but we probably should introduce one at some point. What do you think @hvlads ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@goapunk Well i decided to rename to image to be more semantic, considering the endpoint only allow upload images. Maybe is a good idea an this point create the changelog file and at least include the improvements in the next release, maybe the info:

  • rename url name
  • change view from function to class

]
108 changes: 58 additions & 50 deletions django_ckeditor_5/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@
else:
from django.utils.translation import ugettext_lazy as _

import os
import uuid

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import JsonResponse
from django.views import View
from PIL import Image

from .forms import UploadFileForm
Expand All @@ -19,56 +23,60 @@ class NoImageException(Exception):
pass


def get_storage_class():
storage_setting = getattr(settings, "CKEDITOR_5_FILE_STORAGE", None)
default_storage_setting = getattr(settings, "DEFAULT_FILE_STORAGE", None)
storages_setting = getattr(settings, "STORAGES", {})
default_storage_name = storages_setting.get("default", {}).get("BACKEND")

if storage_setting:
return import_string(storage_setting)
elif default_storage_setting:
try:
return import_string(default_storage_setting)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_setting}"
class UploadImageView(View):
def post(self, request, *args, **kwargs):
if (
request.user.is_staff
or getattr(settings, "CKEDITOR_5_UPLOAD_IMAGES_ALLOW_ALL_USERS", None)
is True
):
form = UploadFileForm(request.POST, request.FILES)
try:
self.image_verify(request.FILES["upload"])
except NoImageException as ex:
return JsonResponse({"error": {"message": f"{ex}"}})
if form.is_valid():
url = self.handle_uploaded_file(request.FILES["upload"])
return JsonResponse({"url": url})
raise Http404(_("Page not found."))

def get_storage_class(self):
juanbits marked this conversation as resolved.
Show resolved Hide resolved
storage_setting = getattr(settings, "CKEDITOR_5_FILE_STORAGE", None)
default_storage_setting = getattr(settings, "DEFAULT_FILE_STORAGE", None)
storages_setting = getattr(settings, "STORAGES", {})
default_storage_name = storages_setting.get("default", {}).get("BACKEND")

if storage_setting:
return import_string(storage_setting)
elif default_storage_setting:
try:
return import_string(default_storage_setting)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_setting}"
raise ImproperlyConfigured(error_msg)
elif default_storage_name:
try:
return import_string(default_storage_name)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_name}"
raise ImproperlyConfigured(error_msg)
else:
error_msg = (
"Either CKEDITOR_5_FILE_STORAGE, DEFAULT_FILE_STORAGE, "
"or STORAGES['default'] setting is required."
)
raise ImproperlyConfigured(error_msg)
elif default_storage_name:
try:
return import_string(default_storage_name)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_name}"
raise ImproperlyConfigured(error_msg)
else:
error_msg = ("Either CKEDITOR_5_FILE_STORAGE, DEFAULT_FILE_STORAGE, "
"or STORAGES['default'] setting is required.")
raise ImproperlyConfigured(error_msg)


storage = get_storage_class()


def image_verify(f):
try:
Image.open(f).verify()
except OSError:
raise NoImageException


def handle_uploaded_file(f):
fs = storage()
filename = fs.save(f.name, f)
return fs.url(filename)


def upload_file(request):
if request.method == "POST" and request.user.is_staff:
form = UploadFileForm(request.POST, request.FILES)
def image_verify(self, f):
try:
image_verify(request.FILES["upload"])
except NoImageException as ex:
return JsonResponse({"error": {"message": f"{ex}"}})
if form.is_valid():
url = handle_uploaded_file(request.FILES["upload"])
return JsonResponse({"url": url})
raise Http404(_("Page not found."))
Image.open(f).verify()
except OSError:
raise NoImageException

def handle_uploaded_file(self, f):
fs = self.get_storage_class()()
filename = f.name.lower()
if getattr(settings, "CKEDITOR_5_UPLOAD_IMAGES_RENAME_UUID", None) is True:
filename = f"{uuid.uuid4()}{os.path.splitext(filename)[1]}"
filesaved = fs.save(filename, f)
return fs.url(filesaved)
15 changes: 10 additions & 5 deletions django_ckeditor_5/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def __init__(self, config_name="default", attrs=None):

def format_error(self, ex):
return "{} {}".format(
_("Check the correct settings.CKEDITOR_5_CONFIGS "), str(ex),
_("Check the correct settings.CKEDITOR_5_CONFIGS "),
str(ex),
)

class Media:
Expand All @@ -54,11 +55,11 @@ class Media:
configs = getattr(settings, "CKEDITOR_5_CONFIGS", None)
if configs is not None:
for config in configs:
language = configs[config].get('language')
language = configs[config].get("language")
if language:
languages = []
if isinstance(language, dict) and language.get('ui'):
language = language.get('ui')
if isinstance(language, dict) and language.get("ui"):
language = language.get("ui")
elif isinstance(language, str):
languages.append(language)
elif isinstance(language, list):
Expand All @@ -80,7 +81,11 @@ def render(self, name, value, attrs=None, renderer=None):

context["config"] = self.config
context["script_id"] = "{}{}".format(attrs["id"], "_script")
context["upload_url"] = reverse("ck_editor_5_upload_file")
context["upload_url"] = reverse(
getattr(
settings, "CKEDITOR_5_UPLOAD_IMAGE_URL_NAME", "ck_editor_5_upload_image"
)
)
context["csrf_cookie_name"] = settings.CSRF_COOKIE_NAME
if self._config_errors:
context["errors"] = ErrorList(self._config_errors)
Expand Down
10 changes: 5 additions & 5 deletions example/blog/tests/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.test import override_settings
from django.utils.module_loading import import_string

from django_ckeditor_5.views import get_storage_class
from django_ckeditor_5.views import UploadImageView


@override_settings(
Expand All @@ -13,20 +13,20 @@
)
def test_get_storage_class(settings):
# Case 1: CKEDITOR_5_FILE_STORAGE is defined
storage_class = get_storage_class()
storage_class = UploadImageView().get_storage_class()
assert storage_class == import_string(settings.CKEDITOR_5_FILE_STORAGE)

# Case 2: DEFAULT_FILE_STORAGE is defined
delattr(settings, "CKEDITOR_5_FILE_STORAGE")
storage_class = get_storage_class()
storage_class = UploadImageView().get_storage_class()
assert storage_class == import_string(settings.DEFAULT_FILE_STORAGE)

# Case 3: STORAGES['default'] is defined
delattr(settings, "DEFAULT_FILE_STORAGE")
storage_class = get_storage_class()
storage_class = UploadImageView().get_storage_class()
assert storage_class == import_string(settings.STORAGES["default"]["BACKEND"])

# Case 4: None of the required settings is defined
delattr(settings, "STORAGES")
with pytest.raises(ImproperlyConfigured):
get_storage_class()
UploadImageView().get_storage_class()
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
def test_upload_file(admin_client, file):
with file as upload:
response = admin_client.post(
reverse("ck_editor_5_upload_file"),
reverse("ck_editor_5_upload_image"),
{"upload": upload},
)
assert response.status_code == 200
Expand All @@ -19,7 +19,7 @@ def test_upload_file(admin_client, file):
def test_upload_file_to_google_cloud(admin_client, file, settings):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test is oddly now failing for me but I think that's because it was not actually using storages.backends.gcloud.GoogleCloudStorage. I added some print statements and on master it uses articles.storage.CustomStorage, somehow override_settings was not working and now is. I'm not entirely sure why. Maybe we can remove this test as I personally don't want to make a request to the google cloud servers every time I run the tests. What do you think @hvlads ?

with file as upload:
response = admin_client.post(
reverse("ck_editor_5_upload_file"),
reverse("ck_editor_5_upload_image"),
{"upload": upload},
)
assert response.status_code == 200
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,4 @@ max-statements = 50 # Recommended: 50
"example/blog/manage.py" = ["TRY003"]
"example/blog/blog/settings.py" = ["N816", "S105"]
"example/blog/tests/*" = ["S101"]
"example/blog/tests/test_upload_file.py" = ["ARG001"]
"example/blog/tests/test_upload_image.py" = ["ARG001"]