Django rest框架可浏览的api在呈现POST表单时呈现PUT和POST表单

时间:2018-05-10 13:02:20

标签: django django-rest-framework

enter image description here

通常当我使用ModelViewSet导航到网址http://localhost:8000/api/v1/public_profiles/时,我只会获得一个POST表单,当我导航到特定资源(例如http://localhost:8000/api/v1/public_profiles/123456/)时,我只会获得PUT / PATCH表单。 目前,这两种表单都在两个位置呈现。

对于我的许多路线,我需要更多地控制我的视图,所以我选择了通用视图。我也想利用路由器,所以我混合了一个通用的视图集。上图是实现以下视图的结果:

class PublicProfileViewSet(viewsets.GenericViewSet, generics.ListCreateAPIView, generics.RetrieveUpdateAPIView):
    queryset = PublicProfile.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return PublicProfileReadSerializer
        elif self.action == 'retrieve':
            return PublicProfileReadSerializer
        elif self.action == 'create':
            return PublicProfileCreateSerializer
        elif self.action == 'update':
            return PublicProfileUpdateSerializer
        else:
            return PublicProfileReadSerializer

我有什么办法可以解决这个问题,以便在LIST操作上呈现POST表单,并在RETRIEVE操作上呈现PUT / PATCH表单吗?

我尝试过的一件事是使用ViewSet但是我没有生成任何表单,因为没有' serializer_class':

class PublicProfileViewSet(viewsets.ViewSet):

     def list(self, request):
         queryset = PublicProfile.objects.all()
         serializer = PublicProfileReadSerializer(queryset, many=True, context={'request': request})
         return Response(serializer.data)

     def retrieve(self, request, pk=None):
         queryset = PublicProfile.objects.all()
         public_profile = get_object_or_404(PublicProfile, pk=pk)
         serializer = PublicProfileReadSerializer(public_profile, context={'request': request})
         return Response(serializer.data)

     def create(self, request):
         serializer = PublicProfileCreateSerializer(data=request.data, context={'request': request})
         if serializer.is_valid(raise_exception=True):
             serializer.save()
             return Response(serializer.data)

     def update(self, request, pk=None):
         instance = get_object_or_404(PublicProfile, pk=pk)
         serializer = PublicProfileUpdateSerializer(instance, data=request.data, context={'request': request})
         if serializer.is_valid(raise_exception=True):
             serializer.save()
             return Response(serializer.data)

     def partial_update(self, request, pk=None):
         instance = get_object_or_404(PublicProfile, pk=pk)
         serializer = PublicProfileUpdateSerializer(instance, data=request.data, context={'request': request}, partial=True)
         if serializer.is_valid(raise_exception=True):
             serializer.save()
             return Response(serializer.data)

     def destroy(self, request, pk=None):
         instance = get_object_or_404(PublicProfile, pk=pk)
         instance.user.is_active = False
         instance.user.save()
         return Response(status=status.HTTP_200_OK)

2 个答案:

答案 0 :(得分:0)

这些表单从Django Rest Framework的默认非JSON Browsable API传播,因为JSON-API仅指定JSON媒体类型。但是制作可浏览的JSON-API接口可能是值得的,尽管我个人更喜欢使用Postman。

查看解析器和渲染器类的设置: REST_FRAMEWORK = { 'PAGE_SIZE': 10, 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.PageNumberPagination', # 'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.LimitOffsetPagination', 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_json_api.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework_json_api.renderers.JSONRenderer', # application/vnd.api+json 'rest_framework.renderers.BrowsableAPIRenderer', # text/html: ?format=api ), 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata', 'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json', 'TEST_REQUEST_RENDERER_CLASSES': ( 'rest_framework_json_api.renderers.JSONRenderer', 'rest_framework.renderers.MultiPartRenderer', 'rest_framework.renderers.TemplateHTMLRenderer' ), }

答案 1 :(得分:0)

确保首先登录。那是我的问题。

enter image description here从{{url}} / admin

登录后

enter image description here 当我登录时