To restrict permissions for the POST method only, you can use the 'permission_classes' attribute in your Django APIView. This attribute can be set to a list of permission classes that should be used for the view.

For example, the following code sets 'permission_classes' to a custom permission class 'IsAuthenticatedOrReadOnly' for the POST method only:

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.response import Response

class MyView(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def post(self, request):
        # handle POST request
        return Response({'message': 'POST method called'})

    def get(self, request):
        # handle GET request
        return Response({'message': 'GET method called'})

In this code, the 'IsAuthenticatedOrReadOnly' permission class will be applied only to the POST method. The GET method will not have any permission restrictions.

You can also use other built-in permission classes like 'AllowAny', 'IsAuthenticated', 'IsAdminUser', etc., based on your requirements.


原文地址: https://www.cveoy.top/t/topic/mlQW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录