djangockeditordjango-ckeditor

How to make ckeditor image upload simple drag and drop


In CKeditor, I did the RichTextUploadingField and all.

Everything working perfectly fine.

I can see the Image button in top menu.

But it is too confusing for user.

Like clicking on image button->upload->select Image->send it to server. It's too much for User. Like I need it very simple image upload in ckeditor.

What I want is simple image uploading. Meaning, User friendly like click on Image button and then drag and drop or select image(Browse) and upload.

There are many thing like image info, link and advanced which I don't want. Because it confuse my users.

Can anyone help me with this? Please.

By the way I am using django-ckeditor==5.9.0


Solution

  • settings.py

    CKEditor Django configurations :

    CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
    
    CKEDITOR_UPLOAD_PATH = 'uploads/'
    CKEDITOR_IMAGE_BACKEND = "pillow"
    
    CKEDITOR_CONFIGS = {
        'default': {
            'toolbar': 'Custom',
            'toolbar_Custom': [
                ['Bold', 'Italic', 'Underline'],
                ['Link', 'Unlink'],
                ['Image'],
            ],
            "filebrowserUploadUrl": "https://mywebsite.com/ckeditor/upload/",
        }
    }
    
    INSTALLED_APPS = [
     ...
     'ckeditor',
     'ckeditor_uploader',
     ...
    ]
    

    Javascript Code to load and upload the image via Ajax :

    function cke_img_upload(input){
        var myFormData = new FormData();
        myFormData.append('upload', input.files[0]);
        $.ajax({
          url: 'http://mywebsite.com/ckeditor/upload/',
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          dataType : 'json',
          data: myFormData,
          success: function (success_data) {
            ckeditor_field = $('.' + $(input).attr('id').replace('img_','')).prev()
            if (ckeditor_field[0]){
                CKEDITOR.instances[ckeditor_field.attr('id')].insertHtml(jQuery('<img/>', {src: success_data['url']}).attr('data-cke-saved-src',success_data['url']).prop('outerHTML'));
            }
          },
          error: function (error_data) {
             console.log(error_data)
          }
        });
    }
    
    function load_image_in_cke(input){
    
        if (input.files && input.files[0]) {
    
        file_extension = input.files[0].name.substring(input.files[0].name.lastIndexOf('.') + 1).toLowerCase();
    
        if (file_extension == "png" || file_extension == "jpeg" || file_extension == "jpg"){
            var reader = new FileReader();
            reader.onload = function (e) {
                cke_img_upload(input)
            }
            reader.readAsDataURL(input.files[0]);
        }
        else{
            show_error_toaster('Only jpg/png formats are supported !!');
        }
      }
    }
    
    CKEDITOR.on('instanceReady', function(event) {
        var cke_toolbox = $('.' + event.editor.id).find('.cke_toolbox')
        cke_toolbox.find('.cke_button__image').closest('.cke_toolbar').remove()
        cloned_copy = $('#custom_img_cke').clone().css('display','initial')
        cloned_copy.find('input').attr('id','img_'+event.editor.id)
        cke_toolbox.append(cloned_copy)
    });
    

    paste this HTML code anywhere in your file where you are using CKEditor :

    <span id="custom_img_cke" class="cke_toolbar cke_toolbar_last" role="toolbar" style="display:none">
    <span class="cke_toolbar_start"></span><span class="cke_toolgroup" role="presentation">
    <label style="margin:20%;cursor:pointer;" id="cke_c" class="cke_button cke_button__image cke_button_off" href="javascript:void('Image')" title="Image"
    tabindex="-1" hidefocus="true" role="button" aria-labelledby="cke_c_label" aria-describedby="cke_c_description" aria-haspopup="false" aria-disabled="false">
    <input type="file" accept="image/jpeg,image/png" onchange="load_image_in_cke(this)" style="display: none; background-color: rgb(235, 235, 235);">
    <span class="cke_button_icon cke_button__image_icon"
    style="background-image:url('/static/ckeditor/ckeditor/plugins/icons.png?t=JB9C');
    background-position:0 -960px;background-size:auto;">&nbsp;</span>
    <span id="cke_c_label" class="cke_button_label cke_button__image_label" aria-hidden="false">Image</span><span id="cke_c_description" class="cke_button_label" aria-hidden="false"></span></label></span><span class="cke_toolbar_end"></span></span>
    

    forms.py

    from django import forms
    import validators as vals
    from ckeditor_uploader.widgets import CKEditorUploadingWidget
    
    class ABCForm(forms.Form):
        abc_description = forms.CharField(max_length=10000, validators=[],
                                                            strip=True,
                                                            required=False,
                                               widget=CKEditorUploadingWidget(attrs={
                                               'data-field': 'abc_description',
                                               "class": "form-control abc_description",
                                               'placeholder': 'ABC Description'}))
    

    urls.py

    from django.views.decorators.cache import never_cache
    from ckeditor_uploader import views as ckeditor_views
    
    
    urlpatterns = [
    ...
    url(r'^ckeditor/upload/', ckeditor_views.upload, name='ckeditor_upload'),
    url(r'^ckeditor/browse/', never_cache(login_required(ckeditor_views.browse)), name='ckeditor_browse'),
    ...
    ]