Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF - make an resource alias /me for current user

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

like image 452
Aldarund Avatar asked Mar 15 '16 14:03

Aldarund


1 Answers

I haven't tested this, as I don't use ViewSets myself, but I believe you could do something like this:

In your urls.py:

from django.conf.urls import url
from rest_framework import routers

from . import views


router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^users/me/$', views.UserViewSet.as_view(), kwargs={'pk': 'me'}),
    url(r'^', include(router.urls)),
]

In your views.py:

from rest_framework import viewsets

from .models import User
from .serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        if self.kwargs.get('pk', None) == 'me':
            self.kwargs['pk'] = self.request.user.pk
        return super(UserViewSet, self).get_object()

Again, this is entirely untested, and entirely theoretical, but something of this sort should work.

like image 97
Joey Wilhelm Avatar answered Sep 30 '22 14:09

Joey Wilhelm