无法上传图片Django REST

niwlg2el  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(125)

我试图通过django rest框架API上传图像,但我没有得到正确的形式。

models.pyin my 'core' app:

def office_image_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = f'{uuid.uuid4()}.{ext}'

    return os.path.join('uploads/office/', filename)

class Office(models.Model):
    # Other fields...
    image = models.ImageField(null=True, upload_to=office_image_file_path)

serializer.pyin 'office' app:

class OfficeSerializer(serializers.ModelSerializer):    
    class Meta:
        """Meta class for OfficeSerializer."""

        model = Office
        fields = "__all__"

class OfficeImageSerializer(serializers.ModelSerializer):
    """Serializer for uploading images to recipes"""

    class Meta:
        model = Office
        fields = ('id', 'image')
        read_only_fields = ('id',)
        extra_kwargs = {'image': {'required': True}}

views.pyin 'office' app:

class OfficeViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows offices to be viewed or edited if authenticated.
    """
    queryset = Office.objects.all()
    serializer_class = OfficeSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """
        Retrive offices for authenticated users.
        """
        return self.queryset.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'upload_image':
            return OfficeImageSerializer

        return OfficeSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    @action(methods=['POST'], detail=True, url_path='upload-image')
    def upload_image(self, request, pk=None):
        office = self.get_object()
        print(request.data)  # Debug: Print the request data
        serializer = self.get_serializer(
            office,
            data=request.data
        )

        if serializer.is_valid():
            serializer.save()
            return Response(
                serializer.data,
                status=status.HTTP_200_OK
            )

        return Response(
            serializer.errors,
            status=status.HTTP_400_BAD_REQUEST
        )

在Swagger中,当我尝试通过/office/office/{id}/upload-image/上传图像时,我没有得到“选择文件”按钮。相反,我得到一个字符串($uri)字段,我不能执行文件上传。我已经在setting.py文件中设置了MEDIA_URL和MEDIA_ROOT。
我期待一个像这样的形式:

但是得到了:

xurqigkl

xurqigkl1#

图片不会被添加到请求的主体中,而是被添加到请求FILES中:

request.FILES.get("NAME_OF_THE_IMAGE")

所以即使你在Postman中做这样的事情:

图像将被添加到请求的FILES部分。现在,NAME_OF_THE_IMAGE并不是你添加的图像的名称,而是“键”(看截图)。

brgchamk

brgchamk2#

通过在settings.py中添加以下内容,可以将FileField设置为二进制:

SPECTACULAR_SETTINGS = {
    'COMPONENT_SPLIT_REQUEST': True
}

这样做,“选择文件”将出现。

相关问题