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

后端 未结 7 1876
陌清茗
陌清茗 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:19

    I have two solutions...

    urls.py

    1) If you are using a router.register, you can add the base_name:

    router.register(r'users', views.UserViewSet, base_name='users')
    urlpatterns = [    
        url(r'', include(router.urls)),
    ]
    

    2) If you have something like this:

    urlpatterns = [    
        url(r'^user/$', views.UserRequestViewSet.as_view()),
    ]
    

    You have to pass the context to the serializer:

    views.py

    class UserRequestViewSet(APIView):            
        def get(self, request, pk=None, format=None):
            user = ...    
            serializer_context = {
                'request': request,
            }
            serializer = api_serializers.UserSerializer(user, context=serializer_context)    
            return Response(serializer.data)
    

    Like this you can continue to use the url on your serializer: serializers.py

    ...
    url = serializers.HyperlinkedIdentityField(view_name="user")
    ...
    

提交回复
热议问题