Kourosh
Kourosh

Reputation: 1074

How to retrieve user id from token?

There is a Plan model that has a user field and I want to fill the user field with user's token so that user can not send user id to create the model for another user and just send post request for themself, here is my model:

class Plan(models.Model):
"""Plan object"""
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    on_delete=models.CASCADE
)

and my view is:

class PlanViewSets(viewsets.ModelViewSet):
"""A viewset for non-admin user see list and admin can curd plan model"""
model = Plan
queryset = Plan.objects.all().order_by('-id')
serializer_class = serializers.PlanSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication,)

def get_queryset(self):
    """retrieve plan just for its own user who is authenticated already"""
    return self.queryset.filter(user=self.request.user)

How to create Plan just for user without getting user field by request body?

Upvotes: 0

Views: 121

Answers (1)

token
token

Reputation: 933

What you want is perform_create method:

class PlanViewSets(viewsets.ModelViewSet):
    """A viewset for non-admin user see list and admin can curd plan model"""
    model = Plan
    queryset = Plan.objects.all().order_by('-id')
    serializer_class = serializers.PlanSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication,)

    def get_queryset(self):
        """retrieve plan just for its own user who is authenticated already"""
        return self.queryset.filter(user=self.request.user)

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

Upvotes: 1

Related Questions