如何添加@permission_classes([IsAuthenticated])只检查POST方法IsAuthenticated?
@api_view(['GET', 'POST'])
def products_list(request):
"""
List of all Products, or create a new Products.
"""
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
注:没有分裂成两个函数,我需要一个单一的视图。
你可以像这样重写IsAuthenticated权限:
class IsAuthenticated(BasePermission):
def has_permission(self, request, view):
if request.method == "GET":
return True
return bool(request.user and request.user.is_authenticated)
IsAuthenticatedOrReadOnly
解决了我的问题。
@permission_classes([IsAuthenticatedOrReadOnly])
见:https://www.django-rest-framework.org/api-guide/permissions/isauthenticatedorreadonly