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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With