Django APIView: Setting Permissions for POST Method Only
To set permissions for a specific HTTP method in Django's APIView, you can use the 'permission_classes' attribute. To apply a permission class to the POST method only, you can define it like this:
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
class MyView(APIView):
def get(self, request):
# your code for GET request
permission_classes = [AllowAny] # applies to all HTTP methods
def post(self, request):
# your code for POST request
self.permission_classes = [IsAuthenticated] # applies to POST method only
In the above example, the 'AllowAny' permission class is applied to all HTTP methods by default. However, for the POST method, the permission class is changed to 'IsAuthenticated' which requires the user to be authenticated in order to access the view.
This approach allows you to have different permission classes for different HTTP methods in the same view.
原文地址: https://www.cveoy.top/t/topic/mlRn 著作权归作者所有。请勿转载和采集!