I have following functions in rest API for User model. I want to set AllowAny permission on only POST request. Can someone help me out.
class UserList(APIView):
"""Get and post users data."""
def get(self, request, format=None):
"""Get users."""
users = User.objects.all()
serialized_users = UserSerializer(users, many=True)
return Response(serialized_users.data)
def post(self, request, format=None):
"""Post users."""
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
http://www.django-rest-framework.org/api-guide/permissions/
as per above URL you have to write one custom permission class
Write your own logic using AllowAny or IsAuthenticated inside MyCUstomAuthenticated based on POST and GET
You can write a custom Permission class
IsPostOrIsAuthenticated
which will allow unrestricted access toPOST
requests but will allow only authenticatedGET
requests.To implement the custom permission
IsPostOrIsAuthenticated
, override theBasePermission
class and implement.has_permission(self, request, view)
method. The method should returnTrue
if the request should be granted access, andFalse
otherwise.So, all
POST
requests will be granted unrestricted access. For other requests, authentication will be required.Now, you need to include this custom permission class in your global settings.