0

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

pacdev
  • 551
  • 1
  • 3
  • 13
  • 1
    `ModelViewSet` is a class composed of mixins. [See here](https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py#L239) Just use `mixins.CreateModelMixin` and ` GenericViewSet` – Ross Rogers Mar 06 '23 at 17:43

1 Answers1

0

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


  • you are right thanks ! Basically I made 2 separate viewset so that the browsable API is working for list and create. – pacdev Mar 08 '23 at 08:04