Search code examples
django-rest-frameworkdjango-viewsdjango-rest-framework-permissions

How to all only post method in a view set in Django REST_framework?


I have a Django REST_framework api and I have a UserViewSet class. For this view set I would like that anyone reaching the url can use the post method of the Viewset but cannot see all the users registered in the database.

Here is my views.py

# Create your views here.
class IsGetMethod(permissions.BasePermission):

    def has_permission(self, request, view):
        # Always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return False
        else:
            return True

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()
    permission_classes = [IsGetMethod]

When I do this, I cannot use the get method when I am not authenticated (which is what I want) but I can't neither use the post method.

Basically what I would like is to have only this post form when I am not authenticated. (highlighted in red below) and not all the list from the get method. The get method should be only for admin authenticated user.

enter image description here


Solution

  • basically you can use POST method but the main problem is that you are accessing endpoint with browser that sends a GET request first and you get permission error.Try using postman and so on for testing endpoints.

    And finally modify your permission class:

    
        def has_permission(self, request, view):
            if (request.user and request.user.is_staff) or request.method == "POST":
                return True
            if request.method in SAFE_METHODS:
                return False
            else:
                return True