2

I'm trying to create a web app for my final school project and i decided to use CKEditor5 to create rich test posts i managed to integrate Ckeditor with Django and, i can successfully create post from the admin aria and add images but when i wanted to do the same thing from the frontend (react), i faced some problems that i didn't know how to solve .

so when i try to upload an image i recive a popup in the browser with the message ** can't upload the file **

this is my code for the editor (it works just fine with text )

<CKEditor
              editor={ClassicEditor}
              data=""
              onInit={(editor) => {
                // You can store the "editor" and use when it is needed.
                console.log("Editor is ready to use!", editor);
              }}
              onChange={(event, editor) => {
                const data = editor.getData();
                this.setState({ content: editor.getData() });
              }}
              onBlur={(event, editor) => {}}
              onFocus={(event, editor) => {
                console.log("Focus.", editor);
              }}
              config={{
                ckfinder: {
                  // Upload the images to the server using the CKFinder QuickUpload command.
                  uploadUrl: "http://localhost:8000/media/uploads/",
                  options: {
                    resourceType: "Images",
                  },
                },
              }}
            />

the url path that i but in the uploadUrl is the path where i put media when using the admin ckeditor that i integrated sepreatly i followed i tutorial to do it

this is the variables that i set in the sittings file

STATIC_URL = '/static/'
STATIC_ROOT = 'static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = 'media/'


CKEDITOR_UPLOAD_PATH = 'uploads/'

so i think that i should not use the same path because i can not POST to this url i get in the local host console an error

Forbidden (CSRF token missing or incorrect.): /media/uploads/
[22/May/2020 08:26:49] "POST /media/uploads/ HTTP/1.1" 403 2513

(i don't use react-create-app server i'm loading react as a django frontend app in port 8000 )

1 Answers1

0

After searching, the solution is that you pass the csrf_token within the headers of your request

So here we need to get first the csrf_token from django session and then pass it to the server

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

The function above will get extract the csrf_token so you can call it and store it in a const

const csrftoken = getCookie('csrftoken');

and then you add the headers to your call

    uploadUrl: "http://localhost:8000/media/uploads/",
    options: {
        resourceType: "Images",
    },
    headers: {
        'X-CSRF-TOKEN': csrftoken,
    }

try that and let me know if that does not work.

As an alternative your can try to wrap your function with the decorator for csrf_exempt to see first is that will work, import it first

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def my_view(request):
Farhani Walid
  • 927
  • 1
  • 9
  • 20
  • i got an error `ReferenceError: jQuery is not defined` and the page didn't load – yahya sghayron May 22 '20 at 08:30
  • i tried importing jquery but im'not sue if i did it the right way – yahya sghayron May 22 '20 at 08:31
  • i got rid of the error but it didn't work the same error as before – yahya sghayron May 22 '20 at 08:36
  • `urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` for the uploadUrl – yahya sghayron May 22 '20 at 08:40
  • try the solution provided in my updated answer, we will see if that work so we can continue to troubleshoot the issue – Farhani Walid May 22 '20 at 20:48
  • i try it but it didn't work i think that the django media path it's not compatible with such operation i think that i should create an other server to serve media files , what you think ? – yahya sghayron May 22 '20 at 20:59
  • maybe because you are trying to upload the file without passing by a view, did this url /media/uploads/ point to a view ? – Farhani Walid May 22 '20 at 21:03
  • what should the view return – yahya sghayron May 22 '20 at 21:08
  • maybe this is the problem, the server is refusing connection for some reason, first lets change this url and delete the http://localhost:8000/ and keep only /media/uploads/ because we are uploading from the same server, and then if it will not work we will try to create a view that will handle the image file and store it in the server – Farhani Walid May 22 '20 at 21:09
  • okey now change the media root to that MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' – Farhani Walid May 22 '20 at 21:21
  • i tried adding ``if settings.DEBUG: urlpatterns += [ re_path(r'^media/(?P.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] `` – yahya sghayron May 22 '20 at 21:35
  • okey lets create a view that will point to the url /media/uploads/ and we will print the request.method at the first place to be sure that is a post request – Farhani Walid May 22 '20 at 21:38