如何从令牌中检索用户 ID?

有一个Plan具有用户字段的模型,我想用用户的令牌填充用户字段,以便用户无法发送用户id为另一个用户创建模型,而只是为自己发送发布请求,这是我的模型:


class Plan(models.Model):

"""Plan object"""

user = models.ForeignKey(

    settings.AUTH_USER_MODEL,

    on_delete=models.CASCADE

)

我的观点是:


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)

如何Plan只为用户创建而不user通过请求正文获取字段?


波斯汪
浏览 86回答 1
1回答

素胚勾勒不出你

你想要的是perform_create方法: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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python