[Django]-Django restful API โ€“ get user id with token

4๐Ÿ‘

#myapp/views.py
class UserIdViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.filter(id=self.request.user.id)

#myapp/urls.py
router.register(r'api/user-id', userviews.UserIdViewSet, base_name="UserId")

sort out the problem. Basically created View set and sort this out against current user.

๐Ÿ‘คRobert

1๐Ÿ‘

What type of authentication you use ?

If for example, you use TokenAuthentication from rest_framework, you can have a look how this class implements request authentication.

You can find there methods authenticate and authenticate_credentials and I believe that there โ€“ you will find your answer how to get the user.

0๐Ÿ‘

In the perform_create method you can assign the user to your model

class EmailViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = Email.objects.all()
    serializer_class = EmailSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

Leave a comment