python Django模型视图集 - 获取当前用户ID

时间:2018-05-03 07:25:29

标签: django python-3.x django-rest-framework

我想获得当前用户ID传递

class document_typeViewSet(viewsets.ModelViewSet):
   user = User.objects.get(id=request.user.id)
   group = user.group.get()
   queryset = document_type.objects.filter(role_id=group)
   serializer_class = document_typeSerializer

我收到错误AttributeError: module 'request' has no attribute 'user'"

2 个答案:

答案 0 :(得分:1)

更新您的代码:

class document_typeViewSet(viewsets.ModelViewSet):
    def function_name(self, request):
        user = User.objects.get(id=request.user.id)
        group = user.group.get()
        queryset = document_type.objects.filter(role_id=group)
        serializer_class = document_typeSerializer

然后你会得到request.user.id

答案 1 :(得分:1)

假设您在USER(新实例创建)时需要creation个实例,那么您必须覆盖create(),如下所示,

class document_typeViewSet(viewsets.ModelViewSet):
    queryset = document_type.objects.filter(role_id=group)
    serializer_class = document_typeSerializer

    def get_user(self, request):
        return request.user

    def create(self, request, *args, **kwargs):
        # create new "document_type" instance
        current_user = request.user
        # do something with "current_user"
        return super().create(request, *args, **kwargs)


同样,如果您有有效logged-in对象

,您可以访问CBV中的request用户