我正在尝试将图像从python客户端发送到django服务器。但是我无法上传文件。 django代码是
models.py
from django.db import models
class File(models.Model):
file = models.FileField()
def __str__(self):
return self.file.name
Serializers.py
from rest_framework import serializers
from .models import File
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = "__all__"
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', FileUploadView.as_view())
]
views.py
class FileUploadView(APIView):
parser_class = (FileUploadParser,)
def post(self, request, *args, **kwargs):
file_serializer = FileSerializer(data=request.FILES)
print(type(file_serializer))
if file_serializer.is_valid():
print('abc')
file_serializer.save()
return Response(file_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
python客户端代码为
import requests as req
name = {'name': open('im.jpeg', 'rb')}
resp = req.post('http://127.0.0.1:8000/upload', name)
print(resp)
print(resp.text)
输出为
{“ file”:[“未提交任何文件。”]}
请帮助我