AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context

后端 未结 7 1875
陌清茗
陌清茗 2021-01-31 03:22

I want to create a many-to-many relationship where one person can be in many clubs and one club can have many persons. I added the models.py and

相关标签:
7条回答
  • 2021-01-31 04:23

    Following Slipstream's answer, I edited my views.py introducing the context and now it works.

    class UserViewSet(viewsets.ModelViewSet):
    
        """
        API endpoint that allows users to be viewed or edited.
        """
        queryset = User.objects.all().select_related('profile').order_by('-date_joined')
        serializer_class = UserSerializer
    
        @list_route(methods=['get'], url_path='username/(?P<username>\w+)')
        def getByUsername(self, request, username):
            serializer_context = {
                'request': request,
            }
            user = get_object_or_404(User, username=username)
            return Response(UserSerializer(user, context=serializer_context).data, status=status.HTTP_200_OK)
    
    0 讨论(0)
提交回复
热议问题