我编写了以下django rest框架视图:
# urls.py
url(r'user/company', views.UserViewSet.as_view({"get": "companyInfo"}), name="company_info"),
# views.py
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
permission_classes = (permissions.IsAuthenticated,)
@action(methods=["get"], detail=True)
def companyInfo(self, request):
user = request.user
company = user.get_company()
detail = {}
detail['company'] = company.name
detail['num_users'] = company.num_licenses if company else None
return Response(detail)
我该如何使用django rest框架编写与“普通” django视图完全相同的视图。例如,如下所示:
# urls.py
path('user/company/', views.company_info, name='company_info'),
# views.py
@require_GET
def company_info(request):
user = request.user
company = user.get_company()
detail = {}
detail['company'] = company.name
detail['num_users'] = company.num_licenses if company else None
return Response(detail)
我想以上只是一个开始,但是我认为我仍然需要正确地进行身份验证(使用jwt),UserViewSet
会自动对permission_classes = (permissions.IsAuthenticated,)
进行认证。
答案 0 :(得分:0)
您非常接近。您可能想要添加两个装饰器,以使其像在ClassView中一样成为经过身份验证的API视图:
# path('user/company/', views.company_info, name='company_info'),
@api_view(['GET'])
@permission_classes((permissions.IsAuthenticated,))
def company_info(request):
user = request.user
company = user.get_company()
detail = {}
detail['company'] = company.name
detail['num_users'] = company.num_licenses if company else None
detail['company_admin'] = company.admin_user.name if company else None
return Response(detail)