我正在Django-React中构建一个应用程序,需要我将一些图像上传到文件夹中。当我提交上传按钮时,在请求上得到错误403。查看控制台,响应显示:&;CSRF失败:CSRF令牌丢失或不正确。&;我试过在views.py中添加@csrf_exempt装饰器,但这不起作用。以下是相关代码的摘录:
settings.py
MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'frontend', 'build', 'static', 'assets')
urls . py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
from woundapp import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('upload/', views.upload_images),
path('admin/', admin.site.urls),
...
re_path(r".*", TemplateView.as_view(template_name="index.html")),
]
urlpatterns = format_suffix_patterns(urlpatterns)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
class Image(models.Model):
image_url = models.ImageField(upload_to='unprocessed/')
serializers.py
from rest_framework import serializers
from .models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = [
'image_url'
]
views.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import os
from .models import Image
from .serializers import ImageSerializer
import requests
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
@api_view(['POST'])
@csrf_exempt
def upload_images(request, format=None):
if request.method == 'POST':
print(request.data.get("images"))
serializer = ImageSerializer(data=request.data, many=True)
if serializer.is_valid():
serializer.save()
images = request.data.get("images")
Image.objects.create(image=images)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
但是,如果我手动从http://127.0.0.1:8000/admin/上传图像,它确实为我工作。
有人能告诉我,如果我做错了什么吗?提前感谢。
我看到一些帖子建议使用@csrf_exempt装饰器,我试过了,但那不起作用。
我认为你需要像这样添加image文件夹的根目录…
MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'upload', 'frontend', 'build', 'static', 'assets')