2

I published my django site but everyday i am finding new problems :) Today i realised my images in the article has no slugify link. Forexample in this page https://www.endustri.io/monokristal-gunes-paneli-nedir-calisma-prensibi-avantajlari/

my tinymce settings is

{
    "height": 500,
    "entity_encoding": "raw",
    "menubar": "file edit view insert format tools table help",
    "plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
    "toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
    "alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | fontsizeselect "
    "emoticons | ",
    "custom_undo_redo_levels": 50,
    "quickbars_insert_toolbar": False,
    "file_picker_callback": """function (cb, value, meta) {
        var input = document.createElement("input");
        input.setAttribute("type", "file");
        if (meta.filetype == "image") {
            input.setAttribute("accept", "image/*");
        }
        if (meta.filetype == "media") {
            input.setAttribute("accept", "video/*");
        }

        input.onchange = function () {
            var file = this.files[0];
            var reader = new FileReader();
            reader.onload = function () {
                var id = "blobid" + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var base64 = reader.result.split(",")[1];
                var blobInfo = blobCache.create(id, file, base64);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            reader.readAsDataURL(file);
        };
        input.click();
    }""",
    "content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",   
}

And i found these codes

'images_upload_handler': 'function(blobInfo, success, failure) {
        var xhr, formData;
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open("POST", "/path/to/upload/handler");
        xhr.onload = function() {
            var json;
            if (xhr.status != 200) {
                failure("HTTP Error: " + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location != "string") {
                failure("Invalid JSON: " + xhr.responseText);
                return;
            }
            success(json.location);
        };
        formData = new FormData();
        formData.append("file", blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
    }',

I added these codes to my actual codes but i recieve an error like this. enter image description here enter image description here

This image has url like this. How can i make this image url like endustri.io/(image or media)/image-name.webp

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApQAAAGVCAMAAAB3pZE2AAAC2VBMVEXz8/Tz8/QoKCktLS4iQX0iRYI6OjwgNmz///8xMTMhQ38hSIchSoo2NjdYWFohPnchOnIhQn5/f4EhR4W+H3DMzM6mpqchRYQhSIYiRoPI0eEhRIJeXl9iYmTX19fIz97p6eoAAACbnaBuRO/Wi/Sf2N27f+CaPUOkapdYxS6xil1jFKrWOUWscotY5Rah2j1DpGqXWMUusYpdb5AlujV99XpgrKAAAAAElFTkSuQmCC

enter image description here

Prusa
  • 157
  • 1
  • 12

1 Answers1

1

You receive these errors because the value of the property 'images_upload_handler' (Line 187) is a JavaScript function that extends over several lines. This JavaScript function is a multi line string, like the JavaString function in Line 161 for the property 'file_picker_callback'. You have to treat the JavaScript function in Line 187 the same way. Write in Line 187

    'images_upload_handler': """function(  ... 

and at the end of the JavaScript functino in Line 208

    }""",

For further Details on multiline strings in Python see https://stackoverflow.com/a/10660443/5655611

Per default, TinyMCE stores images as data URL. This URL contains the data of the whole image. That's why the URL is so long. With data URLs it is possible to embed images directly into HTML. So you can save text, formatting and images i.e. all data of a single document in a single HTML file. That also has advantages.

To save the images separately:

  • Use images_upload_url instead of images_upload_handler. That is easier.
  • If you configure an images_upload_url, a file upload function is already integrated in Tiny Mce. I.e. you don't need file_picker_callback. That means you can use the following for your Tiny Mce settings
{
    "height": 500,
    "entity_encoding": "raw",
    "menubar": "file edit view insert format tools table help",
    "plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
    "toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
    "alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | fontsizeselect "
    "emoticons | ",
    "custom_undo_redo_levels": 50,
    "quickbars_insert_toolbar": False,
    "content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",   
    "images_upload_url": "upload-file",
}

In order for the url upload-file to work, you have to make following adjustments:

Settings.py:

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

Urls.py:

urlpatterns = [
    ...
    path("upload-file", views.upload_file, name="upload_file"),
    ...
]

Views.py:

from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from slugify import slugify
import os
import json
import urllib.parse
@csrf_exempt
def upload_file(request):
    file= request.FILES['file']
    filename= file.name
    filenameParts= os.path.splitext(file.name)
    slugifiedFilename= slugify(filenameParts[0]) + filenameParts[1]
    osFilename= os.path.join(settings.MEDIA_ROOT, slugifiedFilename)
    with open(osFilename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    url= urllib.parse.urljoin( settings.MEDIA_URL, slugifiedFilename)
    data= json.dumps( {"location": url})
    return HttpResponse( data, content_type='application/json')

Attention: Beware of the @csrf_exempt. It could be a security risk. See the django documentation for further information.