我正在关注 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(app)
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 上尝试了其他变体,例如 call token 并使用 'const csrftoken = getCookie('csrftoken');'在 javascript 等中,但我一直在努力弄清楚。
有什么想法吗?
答案 0 :(得分:0)
原来修改端点解决了这个问题。 以前我使用了媒体文件夹的完整网址,如“http://127.0.0.1:8000/media/imageUpload/”。这给了我 Forbidden csrf 错误。 我也尝试过使用“/imageUpload/”,但它给了我“未找到”错误。 因为有一个主要的项目和 post 应用程序,所以我必须指定这样的路由:'/post/imageUpload/'