0

我正在关注https://medium.com/analytics-vidhya/integrating-editorjs-with-django-7a30127d0771的 django-editorjs(django package) 教程。每当我尝试上传图片时,我都会收到此 csrf 错误:禁止(CSRF 令牌丢失或不正确。):/media/imageUpload/ 我设置了媒体根目录和 url,我可以从“http:/”查看示例图片/127.0.0.1:8000/media/imageUpload/example.jpg' 似乎它适用于媒体。但是,本教程涉及使用 @exempt_csrf 和 @requires_csrf_token 上传图像,看起来它会导致 csrf 问题。我尝试了解决方法(例如:https ://github.com/editor-js/image/issues/45 ),添加了带有csrf令牌的additionalRequestHeaders,但它一直显示相同的错误。

这是我的代码:

#urls.py(应用程序)

from django.urls import path, include
from .views import upload_image_view
from django.views.decorators.csrf import csrf_exempt, csrf_protect

urlpatterns = [
    path('imageUpload/', csrf_exempt(upload_image_view)),
]

#urls.py(项目)

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('post/', include('post.urls'), name='post'),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#views.py(功能部分)

from django.shortcuts import render, get_object_or_404, reverse, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie, requires_csrf_token, csrf_exempt
from django.core.files.storage import FileSystemStorage

@requires_csrf_token
def upload_image_view(request):
    f=request.FILES['image']
    fs = FileSystemStorage()
    filename = str(f).split('.')[0]
    file = fs.save(filename, f)
    fileurl = fs.url(file)
    
    return JsonResponse({'success' :1, 'file': {'url': fileurl }})

#models.py

class Post(models.Model):
    title = models.CharField(max_length=200)
    desc = EditorJsField(
        editorjs_config={
            "tools": {
                "Table": {
                    "disabled": False,
                    "inlineToolbar": True,
                    "config": {"rows": 2, "cols": 3,},
                },
                "Image": {
                    "config" : {
                        "endpoints": {
                            "byFile" : 'http://127.0.0.1:8000/media/imageUpload/',
                            "byUrl": 'http://localhost:8000/media/imageUpload/',
                        },
                        "additionalRequestHeaders":[{"Content-Type":'multipart/form-data', "X-CSRF-TOKEN": "{{csrf_token}}" }] #setting it as token(like example from github) won't work because it shows error that it is not defined. I don't know how to call from models.py any idea?
                    }
                }
            }
        }
    )

我尝试了 x-csrf-token 的其他变体,例如调用令牌并使用 'const csrftoken = getCookie('csrftoken');' 在javascript等中,但我一直在试图弄清楚。

有任何想法吗?

4

1 回答 1

0

结果证明修改端点解决了这个问题。以前我使用了媒体文件夹的完整网址,例如“http://127.0.0.1:8000/media/imageUpload/”。这给了我 Forbidden csrf 错误。我也尝试过使用“/imageUpload/”,但它给了我“未找到”错误。因为有一个主项目并遵循发布应用程序,所以我必须像这样指定路线:'/post/imageUpload/'

于 2021-03-04T02:38:24.203 回答