hemo
hemo

Reputation: 110

Removing the primary key in class based views ( django rest framework )

Problem :

Currently in my api/urls.py I have this line

url(r'^profile/(?P<pk>[0-9]+)/$', views.UserProfileView.as_view()),

but I want to get the profile based on request.user and so I have the code in class UserProfileView as the following :

class UserProfileView(generics.RetrieveUpdateAPIView):
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)
    pagination_class = LimitTenPagination

    def get_queryset(self):
        try:
            queryset = UserProfile.objects.filter(user=self.request.user)
        except:
            raise APIException('No profile linked with this user')
        return queryset

But If I remove the pk field from urls.py file, I get an error like this :

AssertionError at /api/profile/

Expected view UserProfileView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

Which is expected.

Possible solution :

I made a function based view like this :

@api_view(['GET', 'PUT'])
def user_detail(request):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        user_profile_data = UserProfile.objects.get(user=request.user)
    except:
        raise APIException('No profile linked with this user')

    if request.method == 'GET':
        serializer = UserProfileSerializer(user_profile_data)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserProfileSerializer(user_profile_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

And in the urls.py file added this line :

url(r'^me/$', views.user_detail),

This gets the work done, but I want a class based solution, so that in case I needed to use pagination_class, permission_class and other features of drf, I can easily use it.

As of now, since I need to fetch only one object, so pagination is out of question.

Thanks.

Upvotes: 2

Views: 1434

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

It is get_object that you need to override for a detail-based view rather than get_queryset.

Upvotes: 3

Related Questions