Home > Net >  permission to class some fields of ViewSet method Django rest framework
permission to class some fields of ViewSet method Django rest framework

Time:10-05

I wanted AllowAny permission only for the retrieve function. In my ViewSets.

class PostLanguageViewSet(viewsets.ViewSet):

    permission_classes = (permissions.AllowAny,)

    permission_classes_per_method = {
        "retrieve": permission_classes
    }

    def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def destroy(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def update(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...
  • this method allows all function permission AllowAny.

CodePudding user response:

try this

class PostLanguageViewSet(viewsets.ViewSet):
    def get_permissions(self):
        if self.request.method == 'GET':
            return [permissions.AllowAny()]
        else:
            return super().get_permissions()

CodePudding user response:

You can use action decorator to achieve this this will override permissions and much more.

class PostLanguageViewSet(viewsets.ViewSet):
    permission_classes = [permissions.AnyOtherPermissionForOtherMethods]

    @action(
        methods=("GET",),
        url_path="get-language",
        url_name="get-language",
        detail=True,
        permission_classes=[
            permissions.AllowAny],
    )
    def retrive_language(self, request, post_id=None, post_language_id=None, *args, **kwargs):
        #Your Code

    def destroy(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def update(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...
        ````
  • Related