@detail_route:对象没有属性 - Django Rest Framework

问题描述 投票:0回答:1

我得到一个关于@detail_route的问题。希望你们的帮助!

这是我的观点。我使用装饰器来导入detail_route

我的观点:

class PhotoUpdateSerializer(ModelSerializer):
    class Meta:
        model = Photo
        fields = [
            'image',
            'is_public',
            'caption'
        ]
class UploadAvatarPhotoAPIView(ReadOnlyModelViewSet):
    serializer_class = PhotoUpdateSerializer
    queryset = Photo.objects.all()

    @detail_route(methods=['POST'])
    def upload_avatar(self, request, username):
        avatarqs = Photo.objects.create(
            user=self.request.user,
            caption=self.caption,
            image=self.image,
            is_public=self.is_public
        )
        serializer = PhotoUpdateSerializer(avatarqs)
        return Response(serializer.data)

错误:'UploadAvatarPhotoAPIView' object has no attribute 'caption'

我认为3行是错误的:

caption=self.caption,
image=self.image,
is_public=self.is_public
django django-rest-framework
1个回答
2
投票

你需要request.POST来获取数据。

caption = request.POST['caption']
is_public = request.POST['is_public']

和图像数据

image=request.FILES.get('image')

UPDATE

您需要在表单标记中将enctype设置为multipart/form-data,以便在上传文件时获取request.FILES中的数据。

<form action="" method="post" enctype="multipart/form-data">
© www.soinside.com 2019 - 2024. All rights reserved.