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

时间:2018-01-03 09:37:40

标签: django django-rest-framework

我遇到了关于@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

1 个答案:

答案 0 :(得分:2)

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

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

和图像数据

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

<强>更新

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

<form action="" method="post" enctype="multipart/form-data">