簡體   English   中英

如何使用(React.js / django /django rest 框架)為 ckeditor 設置 ckfinder?

[英]how to set up ckfinder for ckeditor with ( React.js / django /django rest framework )?

我正在嘗試為我的期末學校項目創建一個 web 應用程序,我決定使用 CKEditor5 創建豐富的測試帖子,我設法將 Ckeditor 與 ZEF0F93C83E374876A61DA0D4D16F36 集成,並且可以在 iAB 成功創建時添加圖片從前端(反應)做同樣的事情,我遇到了一些我不知道如何解決的問題。

因此,當我嘗試上傳圖像時,我會在瀏覽器中收到一個彈出窗口,其中包含消息 ** 無法上傳文件 **

這是我的編輯器代碼(它適用於文本)

<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",
                  },
                },
              }}
            />

我在uploadUrl中的url路徑是我使用管理員ckeditor時放置媒體的路徑,我單獨集成了我按照我的教程去做

這是我在坐在文件中設置的變量

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

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


CKEDITOR_UPLOAD_PATH = 'uploads/'

所以我認為我不應該使用相同的路徑,因為我無法發布到這個 url 我在本地主機控制台中出現錯誤

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

(我不使用 react-create-app 服務器,我將 react 作為端口 8000 中的 django 前端應用程序加載)

搜索后,解決方案是您在請求的標頭中傳遞 csrf_token

所以這里我們需要先從 django session 中獲取 csrf_token 然后傳遞給服務器

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;
}

上面的 function 將提取 csrf_token 以便您可以調用它並將其存儲在 const

const csrftoken = getCookie('csrftoken');

然后將標題添加到您的通話中

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

試試看,如果這不起作用,請告訴我。

作為替代方案,您可以嘗試使用 csrf_exempt 裝飾器包裝您的 function 以首先查看是否可行,請先導入它

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def my_view(request):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM