DRF - make an resource alias /me for current user

Viewed 1687

How to make a resource that will have /user/me url endpoint that will point to current user and behave exactly same as /user/< userid > ( e.g all post, put, delete request done to /user/me should work same way as /user/< userid > ). I see that there is a @detail_route decorator for custom routes, but it seems that inside it i will need to duplicate code there , for each separate request method, which doesnt seem to be a good option. I just need to make an alias for current user. Im talking about ModelViewSet

2 Answers

I too wanted a similar feature where I had a bunch of URLs such as:

  • host_name/api/student/<pk>
  • host_name/api/student/<pk>/something_else

and I wanted the user to be able to access any such URL by replacing with me, and it would automatically substitute 'me' for that user's pk. So I used an improved verison of @Joey Wilhelm's answer.

urls.py:

# original:
path('api/', include(student_router.urls)),

# modified:
path('api/', include(student_router.urls), kwargs={'pk': 'me'}),

views.py:

def dispatch(self, request, *args, **kwargs):
    # we do not want the 'pk' kwarg to appear in non-detail views,
    # since that will give us a "<view> got an unexpected keyword argument 'pk'" error
    if not self.detail:
        kwargs.pop('pk', None)

    else:
        # self.request is not yet populated with the proper user details,
        # so initialize it the same way as in the super method
        req = self.initialize_request(request, *args, **kwargs)

        # replace 'pk' with the user's pk
        kwargs['pk'] = req.user.pk

    return super().dispatch(request, *args, **kwargs)
Related